我有一个模特:
class MyModel(models.Model):
normal = models.CharField(null=True, blank=True, max_length=100)
other = models.CharField(null=True, blank=True, max_length=100)
hidden = models.CharField(null=True, blank=True, max_length=100)
如果我在不使用exclude
的情况下定义常规表单,则隐藏字段会在DOM(和UI)中的提交按钮后显示在UI上:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ('normal', 'hidden')
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(form=self)
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-sm-3 col-md-2'
self.helper.field_class = 'col-sm-9 col-md-10'
self.helper.layout = Layout(
'normal',
Hidden('hidden', 'hidden initial'),
FormActions(
Submit('save', 'Save', css_class='save-entry btn-success'),
)
)
现在如果我翻转并组装一个基本等效的表格但使用exclude
,隐藏的字段就不会出现(这就是我们想要的)。
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
exclude = ('other',)
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(form=self)
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-sm-3 col-md-2'
self.helper.field_class = 'col-sm-9 col-md-10'
self.helper.layout = Layout(
'normal',
Hidden('hidden', 'hidden initial'),
FormActions(
Submit('save', 'Save', css_class='save-entry btn-success'),
)
)
我无法理解为何会发生这种情况。
答案 0 :(得分:2)
Hidden
布局用于创建隐藏输入。您可以添加任何Hidden
元素,即使它未在表单中声明。在您的情况下,如果您检查元素,您可以看到有一个名为hidden
的隐藏输入。
您需要执行以下操作而不是使用Hidden
布局,而需要执行以下操作:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ('normal', 'hidden',)
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(form=self)
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-sm-3 col-md-2'
self.helper.field_class = 'col-sm-9 col-md-10'
self.helper.layout = Layout(
'normal',
Field('hidden', type='hidden'),
FormActions(
Submit('save', 'Save', css_class='save-entry btn-success'),
)
)