Table of contents
1. Use django's own background function to add groups and users
After starting the django service, add an account in the Django terminal
Enter the URL on the web page to jump to the login page
Add a new group, set the name of the group, and save the corresponding permissions
Bind users to groups or set permissions individually
3. Verification of user permissions
This article was written in a hurry, and many places are not perfect. The blogger will continue to update and improve this article. If you don’t understand anything, you can directly comment and find the blogger. The blogger will answer when you see it
the whole idea
1. Use the django background to add users and permissions
2. User login binding
3. Write middleware to verify access to web pages
1. Use django's own background function to add groups and users
After starting the django service, add an account in the Django terminal
python manage.py createsuperuser
Follow the prompts to enter one by one
Don't set the password too simple , just set it here for demonstration
Enter the URL on the web page to jump to the login page
http://127.0.0.1:8000/admin/login
Here are two main functions, Groups and Users
Here is a brief introduction to groups and users. User corresponds to each account, and groupop corresponds to a group. A group can contain multiple accounts. As long as permissions are set for the group, all accounts under the group have corresponding permissions. You can also set different permissions for each account
Groups
Add a new group, set the name of the group, and save the corresponding permissions
The group name added here is [group1], which will be used later
Users
Manage all accounts
Bind users to groups or set permissions individually
The current account 111 is used as a demonstration, and the 111 account is added to group1
So far, the setting is completed by adding users and permissions through the django background, but this is only the corresponding account set, so how to realize the function that only those who belong to the group can access the page of the group on the page, the code part will be introduced below
2. User login binding
login(request, user) can record the corresponding user information, django has already packaged it for us, and we don’t need to do other processing, it has already completed this part of the function
from django.shortcuts import render, redirect
from django.utils.timezone import now
from django.contrib.auth import authenticate, login, logout
# 登录页面
def project_login(request):
if request.method == "GET":
return render(request, '登录页面的html')
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return render(request, '登录成功后的html')
return render(request, '登录页面的html')
3. Verification of user permissions
You can add a decorator to each view, but this is too cumbersome and not conducive to maintenance. Here, groups are used to set permissions. As long as users belong to the corresponding group, they can access the corresponding view. The method used here is to add middleware, so that Before accessing any webpage, it first judges whether it meets a specific group
Create a new py file, enter the following code, and finally remember to register the middleware in settings.py. The order of registering the middleware is also particular . If you don’t understand it, search it yourself. In order to reduce the space, there is no more explanation here.
from django.shortcuts import redirect
from django.urls import reverse
class GroupPermissionMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# 在每个请求之前进行组权限判断
if not self.check_group_permission(request):
return redirect(reverse('需要返回的url地址(一般是登录页,自行决定)'))
response = self.get_response(request)
return response
def check_group_permission(self, request):
# 获取当前请求的用户对象
user = request.user
# 获取当前请求的路径
path = request.path
# 设置需要进行限制访问的路径列表和对应的组
restricted_paths = {
'url存在的路径': '对应的组名',
# 拿刚才创建的group1来举例
'/only_group1/': 'group1',
'/jd/': '对应的组名',
'/vips/': '对应的组名',
}
# 检查用户是否属于指定组,并判断是否允许访问特定页面
for restricted_path, restricted_group in restricted_paths.items():
if restricted_path in path and not user.groups.filter(name=restricted_group).exists():
return False
return True
code explanation
For example, the url I want to visit is http://127.0.0.1:8000/only_group1/show/group1/data/ , then it can be set as the following, as long as there is [/only_group1/] in the url, [group1] is required The permissions of this group, if the user does not belong to the group1 group, it cannot be accessed
restricted_paths = { 'path where url exists': 'corresponding group name', # Take the group1 just created as an example '/only_group1/': 'group1',
'/jd/': 'corresponding group name',
'/vips/': 'corresponding group name',
}