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

Python 如何在Django中实现多个角色?,python,django,django-models,django-forms,Python,Django,Django Models,Django Forms,我想做一个管理角色的应用程序,其中一个用户可以有多个角色。我已经创建了两个模型,一个用于角色,另一个用于models.py中的用户。My models.py的外观如下所示: class Role(models.Model): DOCTOR = 1 NURSE = 2 DIRECTOR = 3 ENGENEER = 4 ROLE_CHOICES = { (DOCTOR, 'doctor'), (NURSE, 'nurse'),

我想做一个管理角色的应用程序,其中一个用户可以有多个角色。我已经创建了两个模型,一个用于角色,另一个用于models.py中的用户。My 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)
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',)
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')
现在我要做的是从用户表单中建立角色。我的forms.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)
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',)
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')
views.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)
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',)
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
表单的子类。ModelForm
也包括:

1)
User
型号中没有
password1
password2
字段-仅
password
。因此,要确认密码,您必须指定
confirm\u password
字段并覆盖
clean
方法以检查它们是否相等

2) 要在表单中显示
角色
,只需在字段列表中指定
“角色”
。由于
角色
字段存在于
用户
模型中,django将找到正确的小部件,正确显示并验证它

3) 你没有写过,但我猜你添加到了
settings.py
?这将把默认的
用户
模型更改为您的应用程序模型

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

class UserCreationForm(forms.ModelForm):
确认\u password=forms.CharField(widget=forms.PasswordInput())
类元:
字段=(‘用户名’、‘密码’、‘确认密码’、‘角色’)
模型=用户
小部件={
“密码”:forms.PasswordInput(),
“角色”:forms.CheckboxSelectMultiple()
}
定义初始化(self,*args,**kwargs):
super()
self.fields['username'].label='Insert username'
self.fields['password'].label='Insert password'
def清洁(自清洁):
cleaned_data=super().clean()
password=已清理的数据。获取(“密码”)
确认密码=已清理的数据。获取(“确认密码”)
如果输入密码!=确认密码:
raise forms.ValidationError(
“密码和确认密码不匹配”
)
实际上,您可能只想使用
OneToOneField
User
ManyToManyField
Role
创建附加模型,而不是覆盖django
User
,因为替换django
User
模型可能会导致问题


退房。您可以使用子类添加
角色

看起来不像
类UserCreationForm(UserCreationForm):
在显示角色选择器的表单中的
字段
变量中的
角色
属性正确,但为空,我如何解决这个问题?您可以使用django admin填充它们。但是我想显示角色选择器。当我尝试在django admin中创建角色时,它会显示一个选择器,其中包含我在模型中定义的角色,是否有一些方法可以执行相同的操作,但在
用户
表单中?是否要直接在表单中动态添加不同的角色?@PaulMiranda我已将表单更新为使用
复选框selectmultiple
for
角色
字段。它非常简单直观,可以从用户表单中选择多个角色。