


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 %}
{% endblock %}
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)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Steps to check the Django version: 1. Open a terminal or command prompt window; 2. Make sure Django has been installed. If Django is not installed, you can use the package management tool to install it and enter the pip install django command; 3. After the installation is complete , you can use python -m django --version to check the Django version.

Django and Flask are both leaders in Python Web frameworks, and they both have their own advantages and applicable scenarios. This article will conduct a comparative analysis of these two frameworks and provide specific code examples. Development Introduction Django is a full-featured Web framework, its main purpose is to quickly develop complex Web applications. Django provides many built-in functions, such as ORM (Object Relational Mapping), forms, authentication, management backend, etc. These features allow Django to handle large

Django is a complete development framework that covers all aspects of the web development life cycle. Currently, this framework is one of the most popular web frameworks worldwide. If you plan to use Django to build your own web applications, then you need to understand the advantages and disadvantages of the Django framework. Here's everything you need to know, including specific code examples. Django advantages: 1. Rapid development-Djang can quickly develop web applications. It provides a rich library and internal

How to upgrade Django version: steps and considerations, specific code examples required Introduction: Django is a powerful Python Web framework that is continuously updated and upgraded to provide better performance and more features. However, for developers using older versions of Django, upgrading Django may face some challenges. This article will introduce the steps and precautions on how to upgrade the Django version, and provide specific code examples. 1. Back up project files before upgrading Djan

django is the backend. Details: Although Django is primarily a backend framework, it is closely related to front-end development. Through features such as Django's template engine, static file management, and RESTful API, front-end developers can collaborate with back-end developers to build powerful, scalable web applications.

The differences are: 1. Django 1.x series: This is an early version of Django, including versions 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8 and 1.9. These versions mainly provide basic web development functions; 2. Django 2.x series: This is the mid-term version of Django, including 2.0, 2.1, 2.2 and other versions; 3. Django 3.x series: This is the latest version series of Django. Including versions 3.0, 3, etc.

How to check the django version: 1. To check through the command line, enter the "python -m django --version" command in the terminal or command line window; 2. To check in the Python interactive environment, enter "import django print(django. get_version())" code; 3. Check the settings file of the Django project and find a list named INSTALLED_APPS, which contains installed application information.

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.
