如何注册 Django 管理员批准?

How to register with Django admin approval?

在我用Django创建的系统中,用户在注册后未经管理员批准不得登录。例如,用户填写注册表后,用户将看到警告

waiting for admin approval

未经管理面板批准无法登录系统。

views.py

def signup(request):

    form_class = SignUpForm
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()  # load the profile instance created by the signal
            user.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            user.first_name = form.data['first_name']
            user.last_name = form.data['last_name']
            user.rank = form.data['rank']
            user.comp_name = form.data['comp_name']
            login(request, user)
            return redirect('/')
    else:
        form = form_class()
    return render(request, 'signup.html', {'form': form})

models.py

class UserProfile(AbstractUser):
    ranks = (
        ('analyst', 'Analyst'),
        ...
    )
    comp_name = models.CharField(max_length=200, default="Choose")
    user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True)
    username = models.CharField(max_length=500, unique=True)
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    password = models.CharField(max_length=50)
    email = models.EmailField(max_length=254)
    rank = models.CharField(max_length=200, choices=ranks)

因此,您正在使用基于内置抽象模型的自定义用户模型。 AbstractUser 模型有一个名为 is_active 的字段,您可以在此处使用。

在注册过程中,将 is_active 的值设置为 False 并使用登录视图的默认 AuthenticationForm 表单。此表单将自动检查 is_active 标志并在 False.

时提供错误

默认错误消息(您可以自定义它们):

error_messages = {
    'invalid_login': _(
        "Please enter a correct %(username)s and password. Note that both "
        "fields may be case-sensitive."
    ),
    'inactive': _("This account is inactive."),
}

您可以从 auth 包中获取表格:

from django.contrib.auth.forms import AuthenticationForm

UserProfile 模型的自定义管理中,为 is_active 标志添加过滤器:

class UserProfileAdmin(admin.ModelAdmin):
    list_filters = ["is_active"]

这样,您将能够列出非活动配置文件并在管理员中激活它们。