Django auth module

First, what is the Auth module

Django Auth module is built-in user authentication module:

In the development of 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.

Django built a powerful user authentication system --auth, it defaults to use ** ** auth_user table to store user data.

Two, auth module commonly used method

from django.contrib import auth

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

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

2.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 (stored into the session table) at the rear end for the user.

Usage:

from django.contrib.auth import authenticate, login
   
def my_view(request):
  username = request.POST['username']
  password = request.POST['password']
  user_obj = authenticate(username=username, password=password)
  if user_obj is not None:
    login(request, user_obj)
    # Redirect to a success page.
    ...
  else:
    # Return an 'invalid login' error message.
    ...

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

2.4 is_authenticated()

It used to determine whether the current request is certified

Usage:

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

2.5 login_required()

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.

LOGIN_URL = '/login/'  # 这里配置成你项目登录页面的路由

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

# 但是偷懒点的用法是:
user_obj = User.objects.create_user(**kwargs) 
# 通常,在校验完数据之后 user_obj.cleaned_data 里面就是键值形式的数据,此时,通过打散就可以作为参数了

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

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

result = user.check_password('密码')

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

2.10 User object properties

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.

Third, extend the default table auth_user

The default auth_user table field does a lot, but in case if you want to use more of the field how to do?

In one method, a new table, and then associate both, you can achieve the purpose of

Another way is to inherit the object inside.

Look closely, auth_user table itself inherited a class: AbstractUser, and all the fields are mapped in AbstractUser table inside. Therefore, on the basis of inheriting this class above plus a custom attribute mapping can be lawlessness.

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
    # 在原本 auth_user 表里面,肯定也有定义的__str__方法,而且返回的就是 self.name,不信你实例化一个对象打印一下试试,返回的肯定是 username

ps:

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 new definition UserInfo table to do user authentication.

But specified and a new custom tables, you need to do is to perform the migration database command to create custom tables in the database, and at this time can not use the default auth_user the table.

Worded as follows:

# 引用 Django 自带的 User 表,继承使用时需要设置
# AUTH_USER_MODEL = "app 名. 类名"
AUTH_USER_MODEL = "app 名. UserInfo"

Reproduced in: https: //www.cnblogs.com/xt12321/p/11052197.html

Guess you like

Origin blog.csdn.net/weixin_34007886/article/details/93382407