Django User authentication system (ii) authentication in Web requests

Source: Internet
Author: User
A Request.user property is provided in each Web request to represent the current user. If the current user is not logged on, this property is an instance of Anonymoususer, and vice versa, is a user instance.

You can differentiate by is_authenticated (), for example:

If request.user.is_authenticated ():
# do something for authenticated users.
Else
# do something for anonymous users.

Login Login

Login ()

The login function requires a HttpRequest object and a user object as arguments. Login () uses the Django session framework to store the user's ID in the session.

Use both authenticate () and login ():

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.
Else
# Return a ' disabled account ' error message
Else
# Return an ' invalid login ' error message.

Sign Out Logout

Logout ()

The HttpRequest object is used as a parameter with no return value. For example:

From Django.contrib.auth Import Logout

def logout_view (Request):
Logout (Request)
# Redirect to a success page.

Restrict access

The raw

Using request.user.is_authenticated ()

Re-orientation:

From django.shortcuts Import redirect

def my_view (Request):
If not request.user.is_authenticated ():
Return redirect ('/login/?next=%s '% request.path)
# ...

Or:

From django.shortcuts Import Render

def my_view (Request):
If not request.user.is_authenticated ():
return render (Request, ' myapp/login_error.html ')
# ...

Using the adorner login_required

Login_required ([Redirect_field_name=redirect_field_name, Login_url=none]

From django.contrib.auth.decorators import login_required

@login_required
def my_view (Request):
...

If the user is not logged in, redirect to Settings. Login_url, and the current URL relative path constitutes a next key query character pair appended to the settings. Login_url Back to:

/accounts/login/?next=/polls/3/.

The key to the query character pair defaults to next and can be named yourself:

From django.contrib.auth.decorators import login_required

@login_required (redirect_field_name= ' My_redirect_field ')
def my_view (Request):
...

You can also define your own Login_url:

From django.contrib.auth.decorators import login_required

@login_required (login_url= '/accounts/login/')
def my_view (Request):
...

urls.py need to define:

(R ' ^accounts/login/$ ', ' django.contrib.auth.views.login '),

Testing the logged-on user

For example, to detect a user's email:

def my_view (Request):
If not ' @example. com ' in Request.user.email:
Return HttpResponse ("You can ' t vote in this poll.")
# ...

Can be used with adorners:

From django.contrib.auth.decorators import user_passes_test

def email_check (user):
Return ' @example. com ' in User.email

@user_passes_test (Email_check)
def my_view (Request):
...

You can also change the Login_url:

@user_passes_test (Email_check, login_url= '/login/')
def my_view (Request):
...

Authentication views

Of course, we can define some of our own login, logout, password management view functions, but also more convenient.

But you can also learn about Django's built-in views.

Django does not provide a default template for the authenticated views, however the template context was documented for each view below.

All built-in views return a Templateresponse instance, allowing you to easily customize response data.

https://github.com/django/django/blob/master/django/contrib/auth/views.py

Most of the built-in authentication views provide a URL name for use.

Login (request[, template_name, Redirect_field_name, Authentication_form,current_app,extra_context])

Source:

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

Parameters:

Template_name: Default login template. The default is registration/login.html.
Redirect_field_name: Redirect name, default to next.
Authentication_form: Default 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: Added to the default context data for the dictionary.

Django.contrib.auth.views.login does:

If accessed through GET, the login form is displayed and its contents can be post to the same URL.
If it is accessed via post, it will first attempt to log in and, if successful, the view will redirect to the link specified by next. If Next is not set, it is redirected to Settings. Login_redirect_url (the general default value is accounts/profile/). If the login fails, the login form is displayed again.

The user is required to provide the login HTML template, the default is registration/login.html. This template will pass 4 template context variables:

Form: A Form object authenticationform.
Next: The redirect link after successful login can contain a query string.
Site: Current website, according to site_id settings. If you do not have the site framework installed, this variable is set to a Requestsite instance, which obtains the site name and domain name from the current HttpRequest.
Site_Name: is an alias of Site.name. If you do not have the site framework installed, it will be set to request. The value of meta[' server_name '].

If you do not want to invoke the registration/login.html template, you can set a specific view parameter in urlconf to pass the Template_name parameter.

(R ' ^accounts/login/$ ', ' Django.contrib.auth.views.login ', {' template_name ': ' myapp/login.html '}),

You can also specify the redirect link field name yourself by using the Redirect_field_name parameter. The default field name is next.

Here is the original state of the registration/login.html template, which assumes you have a base.html template with the definition of content block.

{% extends "base.html"%}

{% block content%}

{% if form.errors%}
<p>your username and password didn ' t match. Please try Again.</p>
{% ENDIF%}

<form method= "POST" action= "{% url ' django.contrib.auth.views.login '%}" >
{% 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>

<input type= "Submit" value= "Login"/>
<input type= "hidden" name= "Next" value= "{{next}}"/>
</form>

{% Endblock%}

If you customize the authentication system, you can pass the custom authentication form to login view via 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 of the user.

URL Name:logout

Optional Parameters:

Next_page: Post-logoff redirect link.

Logout_then_login (request[, Login_url, Current_app, Extra_context])

Log off the user and then redirect to the login link.

Optional Parameters:

Login_url: Redirect link for landing page, default value is settings. Login_url.

Password_change (request[, Template_name, Post_change_redirect,password_change_form,current_app, Extra_context])

Allows the user to modify the password.

URL Name:password_change

Optional Parameters Optional arguments:

Template_name: template name, default value is registration/password_change_form.html.
Post_change_redirect: Redirect link.
Password_change_form: A custom password modification form that includes a user parameter. The default value is Passwordchangeform.

Password_change_done (request[, Template_name,current_app, Extra_context])

The page after the user modifies the password.

URL Name:password_change_done

Optional Parameters Optional arguments:

Template_name: template name, 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])

Send a message to the user with a one-time link that lets the user reset the password.

If the provided mailbox does not exist, it is not sent.

URL Name:password_reset

Optional Parameters Optional arguments:

Template_name: template name, default value is registration/password_reset_form.html.
Email_template_name: Used to generate the template name with the top-up link email, the default value is registration/password_reset_email.html.
Subject_template_name: The name of the template used to generate the message subject, the default value is Registration/password_reset_subject.txt.
Password_reset_form: A form that resets the password, the default value is Passwordresetform.

Token_generator: Check the class instance of the 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: Mail address, 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 the context data that would be is added to the default context data passed to the template.
Html_email_template_name:the full name of a template-to-use-generating a text/html multipart email with the password Reset link. By default, HTML e-mail 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])

Displays the page after the user chooses to send a password reset message. This view is called directly if the Post_reset_redirect link is not explicitly specified in Password_reset () view.

Password_reset_confirm (request[, uidb36, token, template_name, Token_generator,set_password_form, post_reset_ Redirect,current_app, Extra_context])

Displays a form that enters a new password.

Password_reset_complete (request[, Template_name, Current_app, Extra_context])

Reset the password after the form is successful.

Helper functions

Redirect_to_login (next[, Login_url, Redirect_field_name])

Redirect to the login page after the login succeeds in redirecting to another link:

Parameters:

Next: The link after the successful login.

Login_url: Login page link, default defaults: Settings. Login_url.

Redirect_field_name: Redirect field name, the default value is next.

Built-in forms built-in forms

Class Adminpasswordchangeform

User password modification form in admin background

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):
Pass

or allow only active users to log in:

Class Pickyauthenticationform (Authenticationform):
def confirm_login_allowed (self, user):
If not user.is_active:
Raise forms. ValidationError (
_ ("This account is inactive."),
Code= ' inactive ',
)
If User.username.startswith (' B '):
Raise forms. ValidationError (
_ ("Sorry, accounts starting with ' B ' aren ' t welcome here."),
Code= ' No_b_users ',
)

Class Passwordchangeform

Modify the Password form.

Class Passwordresetform

Password reset the form.

Class Setpasswordform

Password setup form.

Class Userchangeform

Admin background user information and permissions to modify the form.

Class Usercreationform

The user creates the form.

Authentication information in the template authentication data in templates

The currently logged on user and their permissions can be obtained in the template variable by using RequestContext.

Users
When rendering the template RequestContext, the current logged-on user, either a user instance or an Anonymoususer instance, is saved in the template variable {{User}}:

{% if user.is_authenticated%}
<p>welcome, {{user.username}}. Thanks for logging in.</p>
{% Else%}
<p>welcome, new user. Please log in.</p>
{% ENDIF%}

If RequestContext is not used, this variable does not exist.

Using RequestContext:

From django.shortcuts import Render_to_response
From django.template import RequestContext

def some_view (Request):
# ...
Return Render_to_response (' my_template.html ',
My_data_dictionary,
Context_instance=requestcontext (Request))

  

The above is the Django user authentication System (ii) the content of the authentication in the Web request, please pay attention to topic.alibabacloud.com (www.php.cn) for more relevant content.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.