Django- comes with user authentication (auth)

auth module

from django.contrib import auth

Method module auth

  1. authenticate()   

    Provides user authentication function, namely to verify the user name and password are correct, it normally takes username, password two key parameters.

    If authentication is successful (valid user name and password are correct), it will return a User object. Otherwise it returns None

    authenticate () sets a property on the rear end of the object to identify User has authenticated the user, and the login information in a subsequent process is required.

    usage:

    user = auth.authenticate(request,username='theuser',password='thepassword')

     

  2. login(HttpRequest, user)

    This function takes an HttpRequest object and a User object certified.

    This function implements a user login functionality. Essentially it generates a session related data for the user at the rear end.

    usage:

    from django.contrib.auth Import the authenticate, Login 
       
    DEF the my_view (Request): 
      username = of request.POST [ ' username ' ] 
      password = of request.POST [ ' password ' ] 
      User = the authenticate (Request, username = username, password = password)
       IF the User IS  not None: 
        the Login (Request, the User) 
        # login is successful, return to success page. 
        ...
       the else :
         # login failures, failure to return the page. 
        ...

     

  3. logout(request) 

    This function takes a HttpRequest object, no return value.

    When the function is called, the current request will clear all session information. Even if the user is not logged in, use this function also does not complain.

    usage:

    from django.contrib.auth import logout
       
    def logout_view(request):
      logout(request)
      # Redirect to a success page.

     

  4. is_authenticated()

    Used to determine whether the current request certified.

    usage:

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

     

  5. login_requierd()

    auth provides us with a decorative tool for quick login to add a check to the view.

    usage:

    from django.contrib.auth.decorators import login_required
          
    @login_required
    def my_view(request):
      ...

    If the user is not logged, it will jump to the django default login URL '/ accounts / login /' and pass the current url to access the absolute path (after a successful landing, will be redirected to the path).

    If you want to customize the login URL, you need to be modified by LOGIN_URL in settings.py file.

    Example:

    = LOGIN_URL ' / the Login / '   # here configured to route the login page of your project

     

  6. create_user()

    Way to create a new user auth offer, it is necessary to provide the necessary parameters (username, password) and so on.

    usage:

    from django.contrib.auth.models import User
    user = User.objects.create_user(username='用户名',password='密码',email='邮箱',...)

     

  7. create_superuser()

    Creating a new super user auth provides a method of providing the necessary parameters (username, password) and so on.

    usage:

    from django.contrib.auth.models Import the User
     # Create a super user must provide mail field, but can provide an empty string 
    the User = User.objects.create_superuser (username = ' username ' , password = ' password ' , Email = ' E-mail ' , ...)

     

  8. check_password(password)

    The correct way to check whether a password auth offer, you need to provide the current request the user's password.

    The password is correct return True, otherwise False.

    usage:

    user.check_password = OK ( ' password ' )

     

  9. set_password(password)

    The method of modifying a password provided by the auth received new password to be set as a parameter.

    Note: After setting sure to call the save method for user objects! ! !

    usage:

    user.set_password(password='')
    user.save()

    A simple example of a change password function

    @login_required
    def set_password(request):
        user = request.user
        err_msg = ''
        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', ''Check the old password is correct#)
            
            IF user.check_password (old_password):
                 IF  not new_password: 
                    ERR_MSG = ' The new password can not be empty ' 
                elif new_password =! repeat_password: 
                    ERR_MSG = ' two passwords do not match ' 
                the else : 
                    user.set_password (new_password) 
                    user.save () 
                    return redirect ( " / Login / " )
             the else : 
                ERR_MSG = ' old password input error ' 
        Content = {
            'err_msg': err_msg,
        }
        return render(request, 'set_password.html', content)
    Change Password Examples

     

Properties User objects

User object properties: username, password

is_staff: whether the user has administrative permissions for the site.

is_active: whether to allow user login, set to False, you can stop users from logging in without deleting the user's premises.

Extend the default table auth_user

This built-in authentication system so easy to use, but auth_user table fields are fixed those few, I can not bring in the project directly ah!

For example, I want to add a field to store the user's mobile phone number, how to do?

Smart you may think of the new table and then another one by one to one and a built-in table auth_user association, although this can meet the requirements, but there is no better way to achieve it?

The answer is of course with.

We can inherit the built-in AbstractUser class to define its own Model class.

This will not only according to the needs of the project design flexible user table, Django can use the strong authentication system.

from django.contrib.auth.models import AbstractUser
class UserInfo(AbstractUser):
    """
    用户信息表
    """
    nid = models.AutoField(primary_key=True)
    phone = models.CharField(max_length=11, null=True, unique=True)
    
    def __str__(self):
        return self.username

note:

After the expansion of the built-in auth_user above table by the way, be sure to tell Django in settings.py, I now use the newly defined UserInfo table I do user authentication. Worded as follows:

# Cited Django comes with the User table, you need to set when inheritance using 
AUTH_USER_MODEL = " App name .UserInfo "

Note again:

Once we specify the table new authentication system used, we need to re-create the table in the database, but can not continue to use the original default auth_user the table .

Guess you like

Origin www.cnblogs.com/wtil/p/11622582.html