我有一个注册表,用户必须在其中选择2个选项之一。
Django可以正确渲染所有图像,django管理员也可以正常显示,但是db将所有可能的选项记录为值。
forms.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
models.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
)中,我需要advertiser
或publisher
,但我所拥有的只是:[('publisher','Publisher'), ('advertiser','Advertiser')]
答案 0 :(得分:0)
如果要在“数据库”字段中提供选择。这样做:
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