Django权限配置咨询:含三类用户角色的应用权限分配实现方案求助
Hey there! Let's walk through building the user creation and permission assignment functionality for your Django app, based on your existing CustomUser model. Here's a practical, step-by-step solution tailored to your needs:
First, let's add role-specific permissions to your CustomUser model if you need granular control over what each role can do. These permissions will let you restrict access to views, data, or actions later on:
class CustomUser(AbstractUser): user_type_data = ((1, "management"), (2, "staff"), (3, "finance")) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) class Meta: # Add custom permissions for each role permissions = [ ("view_staff_dashboard", "Can view staff dashboard"), ("manage_financial_records", "Can manage financial records"), # Add more permissions as your app grows ]
Run makemigrations and migrate after adding these to create the permissions in your database.
Create a form that limits management to only creating staff or accountant users (adjust choices if you want to allow new management users later):
from django import forms from django.contrib.auth.forms import UserCreationForm from .models import CustomUser class StaffAccountantCreationForm(UserCreationForm): # Restrict user type choices to staff and accountant user_type = forms.ChoiceField(choices=[(2, "staff"), (3, "finance")]) class Meta: model = CustomUser fields = ("username", "email", "first_name", "last_name", "user_type", "password1", "password2")
This view will let management users create new staff/accountant accounts and automatically assign the right permissions. We'll lock it down so only management can access it:
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import StaffAccountantCreationForm from django.contrib.auth.models import Permission, Group @login_required def create_staff_or_accountant(request): # Block non-management users from this page if request.user.user_type != "1": return redirect("home") # Redirect to your home page or a forbidden page if request.method == "POST": form = StaffAccountantCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) # Set the user type selected in the form user.user_type = form.cleaned_data["user_type"] user.save() # Assign permissions based on the new user's role if user.user_type == "2": # Staff # Option 1: Assign individual permissions staff_perm = Permission.objects.get(codename="view_staff_dashboard") user.user_permissions.add(staff_perm) # Option 2: Use groups (better for multiple permissions) # staff_group = Group.objects.get(name="Staff") # user.groups.add(staff_group) elif user.user_type == "3": # Accountant/Finance finance_perm = Permission.objects.get(codename="manage_financial_records") user.user_permissions.add(finance_perm) # finance_group = Group.objects.get(name="Finance") # user.groups.add(finance_group) return redirect("user_list") # Redirect to a page showing all users else: form = StaffAccountantCreationForm() return render(request, "create_user.html", {"form": form})
Make a simple template (templates/create_user.html) where management can fill out the form:
<!DOCTYPE html> <html> <head> <title>Add Staff or Accountant</title> </head> <body> <h2>Add New Staff/Accountant User</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Create User</button> </form> </body> </html>
Now you can restrict access to your app's features using the permissions you created. Use Django's permission_required decorator for views:
from django.contrib.auth.decorators import permission_required @permission_required("yourapp.view_staff_dashboard") def staff_dashboard(request): # Staff-only dashboard content here return render(request, "staff_dashboard.html") @permission_required("yourapp.manage_financial_records") def finance_dashboard(request): # Accountant-only financial tools here return render(request, "finance_dashboard.html")
If you plan to add more permissions per role later, using Django's built-in Group model will make management easier. Create groups for Staff and Finance, assign permissions to the groups, then add users to the groups instead of individual permissions. You can set up groups via the Django admin or a management command:
# Example: Run this in a management command or Django shell from django.contrib.auth.models import Group, Permission # Create Staff group and assign permissions staff_group, created = Group.objects.get_or_create(name="Staff") staff_perm = Permission.objects.get(codename="view_staff_dashboard") staff_group.permissions.add(staff_perm) # Create Finance group finance_group, created = Group.objects.get_or_create(name="Finance") finance_perm = Permission.objects.get(codename="manage_financial_records") finance_group.permissions.add(finance_perm)
This way, when you add a new permission to a group, all users in that group automatically get it—no need to update each user individually.
内容的提问来源于stack exchange,提问作者SifuSherif

