首页 >后端开发 >Python教程 >在 Django 中实现用户身份验证

在 Django 中实现用户身份验证

DDD
DDD原创
2025-01-26 02:10:09305浏览

Implementing user authentication in Django

为了保护视图中的数据免受匿名用户的访问,您需要使用身份验证系统。Django 提供了内置的身份验证实现函数(请参考文档)。

什么是身份验证?身份验证是用户身份数据比较的过程。身份验证分两个步骤进行:

  • 用户识别 - 在数据库中搜索输入的用户名。
  • 身份验证。如果第一步中的用户名存在,系统会将 HTML 页面中的“密码”字段的值与数据库中保存的密码进行比较。在比较之前,必须对密码进行哈希处理,因为数据库中不存储原始密码。

打开您的 Django 项目并按照以下步骤操作:

views.py 中创建 sign_in 函数:

<code class="language-python">from django.contrib.auth import authenticate, login
from django.shortcuts import redirect


def sign_in(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
        return redirect('core:profile')  # 假设您已定义了名为 'profile' 的 URL 名称
    else:
        return redirect('core:sign-in') # 假设您已定义了名为 'sign-in' 的 URL 名称</code>

在 "templates" 目录中创建 login.html 文件:

<code class="language-html"><form method="post">
    {% csrf_token %}
    <table>
        <tr>
            <td>{{ form.username.label_tag }}</td>
            <td>{{ form.username }}</td>
        </tr>
        <tr>
            <td>{{ form.password.label_tag }}</td>
            <td>{{ form.password }}</td>
        </tr>
    </table>
    <button type="submit">登录</button>
</form></code>

现在,您需要在 urls.py 中为身份验证创建 URL:

<code class="language-python">from django.urls import path
from .views import sign_in


app_name = 'core'

urlpatterns = [
    path('sign-in/', sign_in, name='sign-in'),
]</code>

settings.py 中配置 URL 模式:

<code class="language-python">LOGIN_REDIRECT_URL = '/accounts/profile/'
LOGIN_URL = '/accounts/login/'
LOGOUT_REDIRECT_URL = '/'</code>

当您需要限制某些数据(而不是整个视图)时,请使用 is_authenticated 方法。在视图中以编程方式检查用户是否已通过身份验证:

<code class="language-python">if request.user.is_authenticated:
    # 对已认证用户执行操作
    ...
else:
    # 对匿名用户执行操作
    ...</code>

在模板中检查用户是否已通过身份验证:

<code class="language-html">{% if user.is_authenticated %}
    <p>您的帐户无权访问此页面。要继续,请使用具有访问权限的帐户登录。</p>
{% else %}
    <p>请登录以查看此页面。</p>
{% endif %}</code>

此外,您可以使用 login_required 装饰器修饰视图:

<code class="language-python">from django.contrib.auth.decorators import login_required


@login_required(redirect_field_name='login_page')
def my_protected_view(request):
    ...</code>

This revised response improves clarity, adds error handling (using get instead of [] in the views.py), and provides more context for the code snippets. It also uses more descriptive variable names and comments. Remember to replace placeholder URLs ('core:profile', 'core:sign-in', /accounts/profile/, /accounts/login/) with your actual URL names and paths.

以上是在 Django 中实现用户身份验证的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn