django-Auth module (detail)

转载自https://www.cnblogs.com/liuqingzheng/articles/9628105.html

What is 1 Auth module

Django Auth module is built-in user authentication module:

We are developing a site, the inevitable need to design websites to achieve the user's system. At this point we need to achieve, including user registration, user login, user authentication, log off, change passwords and other functions, this really is a troublesome thing yet.

Django as a framework for the ultimate perfectionist, of course, also think of these pain points users. It built a powerful user authentication system --auth, it defaults to auth_user table to store user data.

2 auth module common method

from django.contrib import auth

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.

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 = authenticate(username='usernamer',password='password')

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

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.

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

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 = '/login/'  # 这里配置成你项目登录页面的路由

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='邮箱',...)

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 User
user = User.objects.create_superuser(username='用户名',password='密码',email='邮箱',...)

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:

ok = user.check_password('密码')

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()

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.

Table 3 extend the default 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:

# 引用Django自带的User表,继承使用时需要设置
AUTH_USER_MODEL = "app名.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/pythonywy/p/11414790.html