繁体   English   中英

如何在Django中实现多个角色?

[英]How to implement multiple roles in Django?

我想创建一个具有管理角色的应用程序,并且一个用户可以拥有多个角色。 我在models.py中创建了两个模型,一个用于角色,另一个用于Users。 我的models.py看起来像这样:

class Role(models.Model):
    DOCTOR = 1
    NURSE = 2
    DIRECTOR = 3
    ENGENEER = 4
    ROLE_CHOICES = {
        (DOCTOR, 'doctor'),
        (NURSE, 'nurse'),
        (DIRECTOR, 'director'),
        (ENGENEER, 'engeneer'),
    }

    id = models.PositiveIntegerField(choices = ROLE_CHOICES, primary_key = True)

    def __str__(self):
        return self.get_id_display()

class User(AbstractUser):
    roles = models.ManyToManyField(Role)

现在,我要做的是从“用户”表单中建立角色。 我的forms.py看起来像这样:

class UserCreationForm(UserCreationForm):
    fields = ('username', 'password1', 'password2')
    model = User

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['username'].label = 'Insert username'
        self.fields['password1'].label = 'Insert password'
        self.fields['password2'].label = 'Again'


class RoleCreationForm(forms.ModelForm):
    class Meta:
        model = Role
        fields = ('id',)

而且views.py看起来像这样:

class UserCreateView(CreateView):
    model = User
    form_class = forms.UserCreationForm
    template_name = 'user_form.html'
    redirect_field_name = 'index.html'
    success_url = reverse_lazy('accounts:index')

class RoleCreateView(CreateView):
    model = Role
    form_class = forms.RoleCreationForm
    template_name = 'role_form.html'
    redirect_field_name = 'index.html'
    success_url = reverse_lazy('accounts:index')

如何在“用户”表单中显示所有角色并从中选择多个角色?

我假设你UserCreationForm是子类forms.ModelForm还有:

1)没有password1password2在外地User模式-只有password 因此,要进行密码确认,您必须指定confirm_password字段并覆盖clean方法以检查它们是否相等。

2)要以表单形式显示roles ,您只需在字段列表中指定'roles' 由于User模型中存在roles字段,因此django将找到正确的窗口小部件,并对其进行正确显示和验证。

3)您没有写过它,但是我想您在settings.py添加了AUTH_USER_MODEL = '<you_app_name>.User' 这会将默认User模型更改为您的应用程序模型。

4)您的UserCreateView将以纯文本形式存储密码,这是一个非常糟糕的主意。 阅读有关密码管理的更多信息,以了解如何正确存储密码。

class UserCreationForm(forms.ModelForm):
    confirm_password = forms.CharField(widget=forms.PasswordInput())

    class Meta:
        fields = ('username', 'password', 'confirm_password', 'roles')
        model = User
        widgets = {
            'password': forms.PasswordInput(),
            'roles': forms.CheckboxSelectMultiple()
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['username'].label = 'Insert username'
        self.fields['password'].label = 'Insert password'

    def clean(self):
        cleaned_data = super().clean()

        password = cleaned_data.get("password")
        confirm_password = cleaned_data.get("confirm_password")

        if password != confirm_password:
            raise forms.ValidationError(
                "password and confirm_password does not match"
            )

实际上,您可能只想创建OneToOneFieldUserManyToManyFieldRole其他模型,而不是覆盖django User ,因为替换django User模型可能会导致问题。

查看django身份验证视图 您可以将AuthenticationForm子类化以添加Roles

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM