django auth and user


django 自带的 auth 模块需要收先创建数据库才能够使用:

python migrate auth
python migrate

request.user.is_anonymous 检查用户是否是匿名用户

django comes with login/logout forms and views

from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth import views as auth_views
urlpatterns = [
    url(r'^login/$', auth_views.login, name='login'),
    url(r'^logout/$', auth_views.logout, name='logout'),

By default, the django.contrib.auth.views.login view will try to render the registration/login.html template.  and will redirct to the /accouts/profile page

{% extends 'base.html' %}
 {% block title %}Login{% endblock %} 
{% block content %}
<form method="post"> 
{% csrf_token %} 
{{ form.as_p }}
 <button type="submit">Login</button>
{% endblock %}

You can change what django renders

url(r'^login/$', auth_views.login, {'template_name': 'core/login.html'}, name='login'),

You can change where django redirects

LOGIN_REDIRECT_URL = 'home' # in


by default, renders the registration/logged_out.html

url(r'^logout/$', auth_views.logout, {'template_name': 'logged_out.html'}, name='logout'),

url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),

Note the difference, you don’t have to do anything when visiting /logout, the system will just log you out and send you to another page or render a logged out page

Side notes: why changing the redirect url is different with login? find it out later


多年大厂求职&面试官经验,简历付费优化,¥ 500/次。


About 逸飞



邮箱地址不会被公开。 必填项已用*标注