首页 > 解决方案 > 单选按钮错误地写入 django 中的数据库

问题描述

我有一个注册表单,用户必须在其中选择 2 个选项之一。

Django 全部正确渲染,django admin 也可以,但是 db 将所有可能的选择记录为值。

表格.py

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()
    class Meta:
        model = User
        fields = ['username', 'email','password1','password2']

class UserProfileForm(forms.ModelForm):
    terms_compliance = forms.BooleanField(label=mark_safe('I agree with <a href="/questions/whyname/" target="_blank">terms and conditions </a>'))
    class Meta:
        model = UserProfile
        widgets = {'role': forms.RadioSelect}
        fields = ('role','terms_compliance')
        def __init__(self):
            self.fields['terms_compliance'].initial  = True

模型.py

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    role_choices = [('publisher','Publisher'), ('advertiser','Advertiser')]
    role = models.CharField(max_length=15, choices=role_choices, default=None)
    terms_compliance = models.BooleanField()
    def __str__(self):
        return self.user.username

在新实例(即user.userprofile.role_choices)中,我需要advertiseror publisher,但我所拥有的只是:[('publisher','Publisher'), ('advertiser','Advertiser')]

标签: pythondjangodjango-models

解决方案


如果您想在数据库字段中提供选择。这样做:

class UserProfile(models.Model):

    class RoleChoice(ChoiceEnum):
        PUBLISHER = 'Издатель'
        ADVERTISER = 'Рекламодатель'

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    role = models.CharField(max_length=15, choices=RoleChoice.choices(), default=None)
    terms_compliance = models.BooleanField()

    def __str__(self):
        return self.user

在 Views.py 中,像这样填充数据库。

例如:

...
choice = request.query_params.get('choice') or UserProfile.RoleChoice.PUBLISHER.value
...

有关更多详细信息,请从此处阅读:https ://django-mysql.readthedocs.io/en/latest/model_fields/enum_field.html


推荐阅读