python - 单选按钮错误地写入 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
)中,我需要advertiser
or publisher
,但我所拥有的只是:[('publisher','Publisher'), ('advertiser','Advertiser')]
解决方案
如果您想在数据库字段中提供选择。这样做:
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
推荐阅读
- model-view-controller - 我应该在分层架构中的哪一层放置 websocket 调用?
- sql-server - 根据临近日期执行加入
- c++ - 如何从 .pro 文件的列表中删除某些文件?
- laravel-8 - 会话数据在“升级”到 Laravel 8 后大约 4 分钟到期
- javascript - 使用 python 通过 Tor 匿名 scape javascript 信息
- c++ - 链表模板实现和运算符重载
- angular - 被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头
- gmail-api - 如何创建临时 g-mail 帐户
- python - URL 上的多次迭代
- tcl - TCL TK checkbutton:获取选中按钮列表