Detailed Django Auth module (user authentication)

Source: Internet
Author: User
This article mainly introduces the detailed Django Auth module (user authentication), now share to everyone, but also for everyone to make a reference. Come and see it together.

The Auth module is a kind of encapsulation of the login authentication method, before we get the user name and password, we need to query the user table for the object that has the username and password.

With the Auth module you can easily verify that the user's login information exists in the database.

In addition, Auth also made some encapsulation of the session, so that we could verify whether the user is logged in

The method in Auth

If you want to use the Auth module method, you must first import the Auth module

From Django.contrib Import Auth

There are a number of methods available in Django.contrib.auth, which are mainly about four of them:

1, Authenticate ()

Provide user authentication, that is, verify the user name and password is correct, generally need username password two keyword parameters

If the authentication information is valid, a User object is returned. Authenticate () sets a property on the user object to identify the authenticated backend that authenticated the subscriber, and that information is required during the subsequent logon process. When we try to login a user object that is taken directly from the database without authenticate () will error!!

user = Authenticate (username= ' someone ', password= ' Somepassword ')

2. Login (HttpRequest, user)

The function accepts a HttpRequest object, and an authenticated user object

This function uses the Django session framework to attach information such as session ID to an authenticated user.

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:    Login ( Request, user)    # Redirect to a success page.    ...  else:    # Return an ' invalid login ' error message.    ...

3. Logout (Request) Logout user

The function accepts a HttpRequest object with no return value. When the function is called, the session information for the current request is cleared. Even if the user is not logged in, using this function will not error.

From Django.contrib.auth import logout  def logout_view (request):  logout (Request) # Redirect to a success page.

4. The user object's is_authenticated ()

Requirements:

1 Users can access certain pages after logging in,

2 If the user is not logged in to access the page, jump to the login page directly

3 users in the Jump login interface to complete the login, automatic access to the previous access to the address

Method 1:

Validate directly with Auth's is_authenticated () method

def my_view (Request):   if not request.user.is_authenticated ():      return redirect ('%s?next=%s '% (settings. Login_url, Request.path))

Method 2:

According to Request.user.username, if it is empty, then no sign-in

def my_view (Request):   if not request.user.username:      return redirect ('%s?next=%s '% (settings. Login_url, Request.path))

Method 3:

Django has designed a decorator for this case: Login_requierd ()

From django.contrib.auth.decorators import login_required   @login_requireddef my_view (Request): ...

If the user is not logged in, it jumps to the Django default login URL '/accounts/login/' (this value can be modified through Login_url in the settings file). and passes the absolute path of the current access URL (which is redirected to the path after successful login).

User Object

User Object properties: Username, password (required) password save to database with hashing algorithm

Is_staff: Whether the user has administrative privileges on the site.

Is_active: Whether to allow users to log on, set to "False", you can not delete users to prevent users from logging

2.1, is_authenticated ()

If it is a real User object, the return value is constant true. Used to check if the user has passed the authentication.

Certification does not imply that the user has any permissions or even check whether the user is active, which simply indicates that the user has successfully passed the certification. This method is very important, in the background with request.user.is_authenticated () to determine whether the user is logged in, if True can be displayed to the foreground request.user.name

2.2. Create user

To create a user using the Create_user helper function:

From django.contrib.auth.models Import useruser = User.objects.create_user (username= ", password=", email= ")

2.3, Check_password (passwd)

user = User.objects.get (username= ") if User.check_password (passwd):  ...

The user needs to change the password when the first to let him enter the original password, if the given string passed the password check, return True

Use Set_password () to change the password

user = User.objects.get (username= ") User.set_password (password=") user.save

2.5. Simple example

Registered:

def sign_up (Request): state   = None  if Request.method = = ' POST ':     password = Request. Post.get (' password ', ')    Repeat_password = Request. Post.get (' Repeat_password ', ')    email=request. Post.get (' email ', ')    username = Request. Post.get (' username ', ')    if User.objects.filter (username=username): state        = ' user_exist '    else:        New _user = User.objects.create_user (Username=username, Password=password,email=email)        new_user.save ()         Return redirect ('/book/')  content = {    ' state ': state,    ' user ': None,  }  return render (Request , ' sign_up.html ', content)

Change Password:

@login_requireddef Set_password (Request):  user = Request.user state  = None  if Request.method = = ' POST ':    Old_password = Request. Post.get (' Old_password ', ')    new_password = Request. Post.get (' New_password ', ')    Repeat_password = Request. Post.get (' Repeat_password ', ')    if User.check_password (old_password):      If not new_password: state        = ' Empty '      elif new_password! = Repeat_password: state        = ' Repeat_error '      else:        User.set_password (new_ Password)        user.save ()        return redirect ("/log_in/")    else: state      = ' password_error '  content = {    ' user ': User,    ' state ': state,  }  return render (Request, ' set_password.html ', content)

Create a user table yourself

It is important to note that all of the above actions are for Django Auto-created auth_user tables, we can look at the structure of this table

This is a user table that Django has created for us automatically, and if you use the Auth module, you have to use (or inherit) this table.

The benefit of inheriting tables is that we can add some of the fields we need, and we can use the interfaces, methods provided by the Auth module

Here's how to inherit auth:

1, import the Abstractuser class, and write a custom class, inherit the Abstractuser class, as follows:

From django.contrib.auth.models import Abstractuserclass UserInfo (abstractuser): "" "  User info  " ""  nid = Models. Autofield (primary_key=true)  telephone = models. Charfield (max_length=11, Null=true, unique=true) ...  

It is important to note that the UserInfo table does not need to have duplicate fields in the Auth_User, such as username and password, but can still use these fields directly, and Django will automatically encrypt password

2, after writing this, you also need to configure in the setting.py file:

Auth_user_model = ' Blog. UserInfo '

In this way, Django will know from the blog project models to find userinfo this watch.

Related Article

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.