【发布时间】:2016-05-05 07:36:51
【问题描述】:
我是 django 的新手,我认为到目前为止它很棒。我今天遇到了这个奇怪的问题: 我有这个 FormModel:
class RegisterForm2(UserCreationForm):
mobile2 = forms.CharField(
label=_('Mobile Confirmation'),
max_length=50,
required=True,
widget = forms.TextInput(attrs = {'class':'nocopy'})
)
class Meta:
model = User
fields = ['username', 'mobile', 'mobile2', 'guardian_mobile']
labels = {
'username': _('Government ID'),
}
widgets = {
# workaround since __init__ setting to required doesnt work
'mobile': forms.TextInput(attrs = {'required':''}),
}
def __init__(self, *args, **kwargs):
super(RegisterForm2, self).__init__(*args, **kwargs)
self.fields['mobile'].required = True
现在移动字段在模型中有 blank=True 但我希望它只在表单中是必需的,所以我在 __init__ 中做到了。现在它使该字段成为必填字段,但并未将 required="" 添加到文本输入中。现在,如果我像 mobile2 字段那样覆盖了该字段(并添加了 required=True),我就不会有这个问题了。这是一个问题,因为如果我希望在字段上显示所需的属性,我必须覆盖表单中的字段以添加 required=True 这将违反 DRY 原则。我错过了什么还是这是某种错误?
编辑: 我没有提到我正在使用软盘表格。可能与此有关。我必须进一步调查这个问题。
【问题讨论】:
-
这正是
blank的用途 -
@Sayse 我想将模型字段保留为空白=True,但在模型表单中强制要求=True,而不覆盖整个字段的定义。我可以从 init 中做到这一点,但该字段显示没有“必需的”HTML 属性。
-
哦,所以您正在寻找客户端验证而不是服务器端? Alasdails 的回答涵盖了这一点
标签: python django django-models django-forms django-floppyforms