You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

2. Build a User Creation Form for Management

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")
3. Create a View Restricted to Management

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})
4. Create the User Creation Template

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>
5. Secure Other Views with Permissions

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")
6. Optional: Use Groups for Scalable Permissions

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 02:52:43