Home > Article > Backend Development > Django user authentication system (2) Authentication in Web requests
Provide a request.user attribute in every web request to represent the current user. If the current user is not logged in, this attribute is an instance of AnonymousUser, otherwise, it is a User instance.
You can distinguish it by is_authenticated(), for example:
if request.user.is_authenticated():
# Do something for authenticated users.
else:
# Do something for anonymous users.
Login
login()
The login function requires an HttPRequest object and a User object as parameters. login() uses Django's session framework to store the User's id in the session.
Use authenticate() and login() at the same time:
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
passWord = request.POST[ 'password']
user = authenticate(username=username, password=password) if user is not None:
if user.is_active:
login(request, user)
# Redirect to a success page.
el se:
# Return a 'disabled account' error message
else:
# Return an 'invalid login' error message.
def logout_view(request):
logout(request)
# Redirect to a success page.
def my_view(request):
if not request.user.is_authenticated():
return redirect('/login/?next=%s' % request.path)
# ...
def my_view(request):
if not request.user.is_authenticated():
return render(request, 'myapp/ login_error.html')
# ...
@login_requir ed
def my_view( request):
...
@login_required(redirect_field_name=' my_redirect_field')
def my_view(request):
...
@login_required(login_url='/accounts/login/')
def my_view(request):
...
if not '@example.com' in request.user.email:
return HttpResponse("You can't vote in this poll .")
# ...
def email_check(user):
return '@example.com' in user.email
@user_passes_test(email_check)
def my_view(request):
...
def my_view(request):
...
def login(request, template_name='registration/login.html',
redirect_field_name=REDIRECT_FIELD_NAME,
authentication_form=AuthenticationForm,
current_app=None, extra_context=None):
"""
Displays the login form and handles the login action.
"""
redirect_to = request.POST.get(redirect_field_name,
request.GET.get(redirect_field_name, ''))
if request.method == "POST":
form = authentication_form(request, data=request.POST)
if form.is_valid():
# Ensure the user-originating redirection url is safe.
if not is_safe_url(url=redirect_to, host=request.get_host()):
redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
# Okay, security check complete. Log the user in.
auth_login(request, form.get_user())
return HttpResponseRedirect(redirect_to)
else:
form = authentication_form(request)
current_site = get_current_site(request)
context = {
'form': form,
redirect_field_name: redirect_to,
'site': current_site,
'site_name': current_site.name,
}
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context,
current_app=current_app)
URL name: login
参数:
template_name: 默认的登陆模板.默认为registration/login.html.
redirect_field_name: 重定向的name,默认为next.
authentication_form: 默认Form. Defaults to AuthenticationForm.
current_app: A hint indicating which application contains the current view. See the namespaced URL resolution strategy for more information.
extra_context: 添加到默认context data中的额外数据,为字典。
django.contrib.auth.views.login does:
如果通过GET访问, 将显示登录表单,可以将其内容POST到相同的URL上。
如果通过POST访问,它首先会尝试登录,如果成功,view就重定向到next指定的的链接。如果next 未设置,则重定向到settings.LOGIN_REDIRECT_URL(一般缺省值为accounts/profile/)。如果登录失败,则再次显示登录表单。
需要用户自己来提供login的html模板,缺省是registration/login.html 。这个模板将传递4个模板上下文变量:
form: 一个表单对象AuthenticationForm.
next: 登录成功后的重定向链接,可以包含一个query string中。
site: 当前网站,根据 SITE_ID 设置。如果你并没有安装site框架,这个变量将设定为一个 RequestSite实例,它从当前 HttpRequest中取得站点名和域名。
site_name: 是 site.name的一个别名。如果你没有安装site框架,它将会被设为 request.META['SERVER_NAME']的值。
如果你不想调用registration/login.html模板,你可以在URLconf中设定特定的view参数来传递template_name参数。
(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}),
你也可以自己指定重定向链接字段名,通过redirect_field_name 参数。默认的字段名为next.
下面是registration/login.html 模板的原始状态,它假定你有一个base.html模板(其中有content block的定义。
{% extends "base.html" %}
{% block content %}
{% if form.errors %}
Your username and password didn't match. Please try again. p>
{% endif %}
If you customize the authentication system, you can pass the customized authentication form to the login view through the authentication_form parameter. The form's __init__ method should have a request parameter and provide a get_user method to return the authenticated User object.
logout(request[, next_page, template_name, redirect_field_name, current_app,extra_context])
Log out the user.
URL name: logout
Optional parameters:
next_page: Redirect link after logout.
logout_then_login (request[, login_url, current_app, extra_context])
Log out the user and redirect to the login link.
Optional parameters:
login_url: Redirect link to the login page, the default value is settings.LOGIN_URL.
password_change(request[, template_name, post_change_redirect,password_change_form,current_app, extra_context])
Allows users to change passwords.
URL name: password_change
Optional arguments:
template_name: template name, default value is registration/password_change_form.html .
post_change_redirect: Redirect link.
password_change_form: Customized password change form, including a user parameter. The default value is PasswordChangeForm.
password_change_done(request[, template_name,current_app, extra_context])
The page after the user changes the password.
URL name: password_change_done
Optional arguments Optional arguments:
template_name: template name, The default is registration/password_change_done.html.
password_reset(request[, is_admin_site, template_name, email_template_name, password_reset_form, token_generator, post_reset_redirect, from_email, current_app, extra_context, html_email_template_name])
Sends an email to the user, containing a one-time link , to let the user reset their password.
If the email address provided does not exist, it will not be sent.
URL name: password_reset
Optional arguments Optional arguments:
template_name: Template name, the default value is registration/password_reset_form.html.
email_template_name: The template name used to generate emails with recharge links. The default value is registration/password_reset_email.html.
subject_template_name: The name of the template used to generate email subjects. The default value is registration/password_reset_subject.txt.
password_reset_form: Password reset form, the default value is PasswordResetForm.
token_generator: Check the class instance of one-time link, the default value is default_token_generator, its class is django.contrib.auth.tokens.PasswordResetTokenGenerator.
post_reset_redirect: Redirect link after password reset.
from_email: Email address, the default value is DEFAULT_FROM_EMAIL.
current_app: A hint indicating which application contains the current view. See the namespaced URL resolution strategy for more information.
extra_context: A dictionary of context data that will be added to the default context data passed to the template.
html_email_template_name: The full name of a template to use for generating a text/html multipart email with the password reset link. By default, HTML email is not sent.
Example: registration/password_reset_email.html (email content template):
Someone asked for password reset for email {{ email }}. Follow the link below:
{{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
password_reset_done(request[, template_name])
Display the page after the user chooses to send a password reset email. If the post_reset_redirect link is not explicitly specified in the password_reset() view, this view will be called directly.
password_reset_confirm(request[, uidb36, token, template_name, token_generator,set_password_form, post_reset_redirect,current_app, extra_context])
Display the form for entering a new password.
password_reset_complete(request[, template_name, current_app, extra_context])
Heavy The form after successfully setting the password.
Helper functions
redirect_to_login(next[, login_url, redirect_field_name])
Redirect to the login page. After successful login, redirect to another link. .
Parameters:
next: link after successful login.
login_url: login page link, default value: settings.LOGIN_URL.
redirect_field_name: Redirect field name, the default value is next.
Built-in forms
class AdminPasswordChangeForm
Admin background user password change form
class AuthenticationForm
login form.
Method confirm_login_allowed(user)
For example, allow all users to log in, regardless of the is_active attribute:
from django.contrib.auth.forms import AuthenticationForm
class AuthenticationFormWithInactiveUsersOkay(AuthenticationForm):
def confirm_login_allowed(self , user):
Or only allow active users to log in: use with use with ‐ ‐ ‐ off‐set,
Error(
use with through through through through through out through out through through out through out through out through''s' ‐ ‐ ‐‐‐ way to _(" Sorry, accounts starting with 'b' aren't welcome here. "),
code='no_b_users', wordForm
Password setting form.
class UserChangeForm
User information and permission modification form in the admin background.
class UserCreationForm
User creation form.
Authentication information in templates Authentication data in templates
The currently logged in user and their permissions can be obtained in the template variables by using RequestContext.
Users
When rendering the template RequestContext, the current logged-in user, whether it is a User instance or an AnonymousUser instance, is saved in the template variable {{ user }}:{% if user.is_authenticated %}
Welcome, { { user.username }}. Thanks for logging in.
{% else %}
Welcome, new user.
If RequestContext is not used, this variable does not exist. St Use RequestContext: from django.shortcuts import render_To_Responsefrom django.template Import REQUESTCONTEXTEF SOMEF SOME_View (request):
# ... Return Render_to_Response ('My_template.html',my_data_dictionary,
context_instance = requestContextExt (request))
The above is the authentication content in the Django user authentication system (2) Web request. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!