python - 对于从 CreateView 创建新帐户的新用户,将 is_staff 设置为 true

标签 python django django-forms django-authentication

我在使用 Django 时遇到问题。

我正在使用 UserCreationForm 和通用 CreateView 以便人们注册和创建帐户。代码如下:

自定义表单:

class SignUpCustomUserForm(UserCreationForm):
    first_name = forms.CharField(max_length=200)
    last_name = forms.CharField(max_length=200)
    email = forms.EmailField(max_length=200)

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2']

查看:

class SignUpView(generic.CreateView):
    form_class = SignUpCustomUserForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'

我没有模型,因为我使用的是基本上处理模型的 CreateView。

我想自动将每个新创建的帐户设置为员工,但我不知道该怎么做。基本上,我正在处理一个表单,用户可以使用该表单创建一个具有 is_staff 权限的帐户,他们可以使用这些帐户登录/admin(默认的 django 管理员)。

我尝试在表单类中的 Meta 类中将 model.is_staff 设置为 true,但没有成功。

欢迎任何建议或想法。

谢谢

最佳答案

您可以在.form_valid(…) 方法中将is_staff 设置为True:

class SignUpView(generic.CreateView):
    form_class = SignUpCustomUserForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'
    
    def form_valid(self, form):
        form<strong>.instance.is_staff = True</strong>
        return super().form_valid(form)

关于python - 对于从 CreateView 创建新帐户的新用户,将 is_staff 设置为 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71461048/

相关文章:

python - django-admin - 如何修改 ModelAdmin 以一次创建多个对象?

python - 界定 ModelChoiceField 中的选择

python - 从导入的模块覆盖导入模块的内置函数

python - Model.clean() 与 Model.clean_fields()

javascript - Django 调试工具栏 - Prototypejs 版本

django - 自定义管理导入表单

python - django-allauth 将用户名设置为与电子邮件相同

python - 可变长度列表的列表

python - 从 Python 字典键创建变量

python - 由 <function check_errors.<locals>.wrapper at 0x7fdd43044d90> 启动的线程中出现未处理的异常