Django User authentication

Source: Internet
Author: User
Tags anonymous auth sessions
the first two middleware

Sessions.middleware.SessionMiddleware ', and Authenticationmiddleware middleware is automatically registered to the system when the project is re-created

middleware_classes = (
    ' django.contrib.sessions.middleware.SessionMiddleware ',
    ' Django.middleware.locale.LocaleMiddleware ', '
    django.middleware.common.CommonMiddleware ',
    ' Django.middleware.csrf.CsrfViewMiddleware ',
    ' Django.contrib.auth.middleware.AuthenticationMiddleware ', '
    django.contrib.messages.middleware.MessageMiddleware ',
    ' Django.middleware.transaction.TransactionMiddleware ',

With these two middleware, in view, we can use Request.user to get the current login user object. If the current user does not log in, then Request.user will be the Anonymoususer object we said before. We can use the is_authenticated () method of the user object to differentiate between the two:

If request.user.is_authenticated ():
    # for Authenticated users.
    # for anonymous users who are not logged on
Login to a user

Requires two functions: Authenticate (Username,password) and login (Request,user), located in the Django.contrib.auth module, which need to be used in conjunction with authenticate ( Username,password) function requires two parameter Username,password, if the validation pass returns the user object, if the checksum does not pass by returning none, for example:

From Django.contrib.auth import authenticate
user = Authenticate (username= ' John ', Password= ' secret ')
if user Is isn't None:
    if user.is_active:
        print "You provided a correct username and password!"
        print "Your account has been disabled!"
    print "Your username and password were incorrect."
The. Login () method accepts two parameters, the first one is the request object, and the second is the validated user object. The login method uses Sessionmiddleware to store the UserID in the session. Note that when the user is not logged in, there are also anonymous users of the session, after their landing, before the anonymous session retained information, will remain. These two methods are used in conjunction and must first be called Authenticate (), because the method will record the user's validation on a property, and this property will be used by the subsequent login procedure, for example:
Rom 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 _active:
            Login (Request, user)
            # jumps to the success page.
            # returns an invalid account error
        # Returns the login Failure page.

Additional Sign-in methods

You can also use no authenticate () for a user-specific identity check, directly using a number of user-independent functions for password-related checks, The following methods are available in Django1.4 and in the new version, located in module django.contrib.auth.hashers:

check_password (password,encoded): The first parameter is the plaintext password, The second parameter is a password that has been encrypted. If True is returned by a checksum, not by returning false;
Make_password (Password[,salt,hashers]): Returns an encrypted password based on the given plaintext password, salt, and Django-supported cryptographic algorithms. If password provides a value of None, the return value will never pass the Check_password () method. This return value is a specific contract value, which is now '! ';
Is_password_usable (Encoded_password): Determines whether the given string is a hashed password and has the opportunity to pass the check of the Check_password () function.
Logout (log out) of a user

We use the Django.contrib.auth.logout function to log out the user logged in with the Django.contrib.auth.login function.

Logout (Requet)

The function has only one parameter, which is the request. There is no return value, and no exception is thrown even if the current user is not logged in.

from Django.contrib.auth import logout

def logout_view (request):
    logout (Request)
    # Redirect to successful Logout interface


This method will completely empty the data stored in the user session, so as to avoid someone using the current user's browser login and then can view the current user's data, recall that login will retain the anonymous user's session data. If you need to add something to the user session after the logout, you need to do it after the logout method call.
two signals of login and logout

Django's signal system is a simple and practical set of event definitions, event generation, event monitoring, and event handling frameworks that you can refer to Django's documentation for signal. At these two important points of landing and logout, two signal are provided:

There are three parameters that will pass with Singal:

Sender:user's class, if it is the logout event, the value may be none if the user does not validate at all.
the Request:httprequest object
User:user object, if it is a logout event, the value is probably none if the user does not validate at all.

A recurring simple requirement is to control that certain view (called action method in struts) is only available to the logged-on user, and if the user is not logged in, the view is redirected to the login interface to log in. To do this, we can do this:

From django.http import Httpresponseredirect

def my_view (request):
    if not request.user.is_authenticated ():  
        return Httpresponseredirect ('/login/?next=%s '% request.path)
    # ...
You can also do this by returning an error page:
def my_view (request):
    if not request.user.is_authenticated ():
        return render_to_ Response (' myapp/login_error.html ')
    # ...
the more elegant way is to use decorator:

Django.contrib.auth.decorators.login_required ([Redirect_field_name=redirect_field_name,login_url=none])
The login_required () adorner function does the following things:
If the current user is not logged in, jump to settings. Login_url, and passes the current absolute path to the URL request parameter, for example:/accounts/login/?next=/polls/3/
If the current user has logged in, execute the view method. The method in view can assume that the current user is logged in.

The Login_required method accepts two parameters:

redirect_field_name: The default value is next. Used to define the URL of the access interface before jumping back after successful landing.
Login_url: The default value is settings. Login_url. The URL used to specify the login interface. If you do not pass in the change parameter, you need to ensure settings. The value of the Login_url is set correctly.
How to use login_required adorners without parameters: from

django.contrib.auth.decorators import login_required

@login_ Required
def my_view (request):
Method of passing parameters: from

django.contrib.auth.decorators import login_required

@login_required (redirect_field_name= ' My_redirect_field ')
def my_view (request):
From django.contrib.auth.decorators import login_required

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

The above is what Django provides for the completion of login and logout related API support, using them can be very good authentication to the user, that is, the user who is the system has been made clear, followed by a more granular judgment, to determine what this person can do, That is, the use of the permission license.

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: 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.