This article is participating in Python Theme Month. See the link to the event for more details
Rest cannot be enjoyed by lazy people~
preface
When developing a website, it is inevitable to implement the user system of the website, including user registration, user login, user authentication, user logout and other functions. It is very troublesome to write it yourself. Django, as the ultimate framework for perfectionists, must also consider these issues. Django’s solution to these problems is its powerful built-in user authentication system, Auth. This article will look at django’s auth authentication capabilities in detail.
Introduction to the Auth module
Django provides a very useful component that is responsible for the full set of user login authentication functions. It is called the Auth component. With the Auth component, we no longer need to manually write the login validation decorator, and we no longer need to manually set the session to save the user’s state. The Auth component is closely related to the auth_user table, which is one of the default tables that django projects generate when executing database migration commands. In addition, django projects will have an admin backend by default, and the login user information is stored in the auth_user table. Users are classified into common users and super users. Only the super user can log in to the admin background management system.
python manage.py createsuperuser
The password should be at least 8 characters long. After creating the password, you can log in to Django background management.
Copy the code
Basic use of the auth module
Login verification:auth.authenticate()
from django.contrib import auth
user_obj = auth.authenticate(request,
username=username,
password=password)
print(user_obj)
print(user_obj.username)
# Note:
1.Authenticate () must pass in both user name and password in parentheses2.The password is automatically encrypted and verified3.If the verification succeeds, the object is returned. If the verification fails, the object is returnedNone
Copy the code
Save user state:auth.login()
auth.login(request, user_obj)
request.user # Get the currently logged in user object
# Note:
1.This method requires two methods: request, and the currently logged in user object2.This method automatically sets the session, similar to request.session[key] = user_obj3.Once this method is executed, the currently logged in user object can be retrieved from anywhere via request.userCopy the code
Login decorator: Determines whether the user is logged in
from django.contrib.auth.decorators import login_required
@login_required(login_url='/login/')
def index(request) :
pass
# Note:
1.If you are not logged in, you need to manually set the page. Set up branch Settings and global Settings.2.Local Settings, specified directly in the decorator with the login_URL parameter3.For global Settings, use the LOGIN_URL = parameter in the configuration file'/login/'Set up the4.The decorator helps us add the target_URL after the url after the jump, which we manually capture in the login view function4.Local Settings have a higher priority than global Settings5.The global advantage is that you don't have to write code repeatedly but you don't have to jump to a single page6.The local benefit is that different view functions can jump to different pages when the user is not logged inCopy the code
How do I verify a password change
Request.user.check_password (old_password) - Modify user information request.user.set_password(new_password)# Only modifying the properties of the object
request.user.save() This step is the actual operation of the database
Copy the code
How to log out of the current user:auth.logout(request)
How do users register
# Method 1: write data to table auth_user (not recommended, password is not encrypted)
from django.contrib.auth.models import User
User.objects.create(username=username, password=password)
# Method 2: Create a common user
User.objects.create_user(username=username, password=password)
# Method 3: Create a superuser
User.objects.create_superuser(username=username,
email='[email protected]',
password=password)
# note:
1.way2And the way3Returns the current object after successful creation2.When you create a superuser using code, the mailbox is mandatory, but when you create a superuser using a command, it is notCopy the code
Extension auth_user table
This built-in authentication system is so easy to use, but the auth_user table fields are fixed, I can not use them directly in the project ah!
For example, what if I want to add a field that stores the user’s phone number?
You might be smart enough to create another table and associate it with the built-in auth_user table one to one. That would do the trick, but is there a better way to do it? The answer is yes.
We can define our own Model class by inheriting from the built-in AbstractUser class. This gives you the flexibility to design user tables according to your project requirements, while using Django’s powerful 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
Copy the code
If we inherit from AbstractUser class, The auth_user table will no longer be created when the database migration command is executed, and the UserInfo table will have all the auth_user columns in addition to its own extension fields. The advantage of this is that you can click on your own table to complete the operation and extension more quickly.
But there are several prerequisites for using this method:
The auth_user command is not created. If the current library is already created, then you need to replace it with another library. Do not overwrite field names in an inherited class from AbstractUser. Do not touch any fields in the table, just extend extra fields. You need to tell Django in the configuration file that you want to replace auth_user with UserInfo. AUTH_USER_MODEL = ‘app01.userinfo’ # ‘the application name. If auth_user is replaced by auth_user, the auth module functions as usual, and the reference table page is changed from auth_user to UserInfo
conclusion
The article was first published in the wechat public account program Yuan Xiaozhuang, synchronized with nuggets.
Please explain where it came from. If you pass by, please put out your cute little finger and click like before you go (╹▽╹)