Django 认证登录 authenticate

192 阅读1分钟
  1. 在DTL模板中:
{% if user.is_authenticated %}
        <span>{{ user }}</span>
        <a href="{% url 'logout' %}">退出</a>
    {% else %}
        <a href="#">signin</a>
        <a href="#">signup</a>
    {% endif %}
  1. 视图 iauth/views 中( iauth 是认证相关的 App ):
def logout_view(request):
    logout(request)
    return redirect('/')

在 urls.py 中:

urlpatterns = [
    ...
    path('logout/', iauth_view.logout_view, name='logout'),
    ...
]
  1. 在 settings.py 中:
TEMPLATES = [
    {
        ...
        
        'OPTIONS': {
            'context_processors': [
                ...
                # 需要添加 auth 上下文处理器,默认已添加
                'django.contrib.auth.context_processors.auth',
                ...
            ],
        },
    },
]