從this question我想將我的表格從常規Form
轉換爲ModelForm
,這樣我就可以利用ModelForm
中的instance
參數。如何以編程方式在Django的ModelForm中設置字段?
這是我目前的形式代碼:
class OrderDetailForm(forms.Form):
def __init__(
self,
user,
can_edit_work_type=None,
can_edit_vendor=None,
can_edit_note=None,
*args,
**kwargs
):
super(OrderDetailForm, self).__init__(*args, **kwargs)
if can_edit_work_type:
self.fields['work_type'] = forms.ChoiceField(choices=Order.WORK_TYPE_CHOICES)
if can_edit_vendor:
self.fields['vendor'] = forms.ModelChoiceField(
queryset=Vendor.objects.all(),
empty_label="Choose a vendor",
)
if can_edit_note:
self.fields['note'] = forms.CharField(widget=forms.Textarea)
def clean(self):
super(OrderDetailForm, self).clean()
if 'note' in self.cleaned_data:
if len(self.cleaned_data['note']) < 50:
self._errors['note'] = self.error_class([u"Please enter a longer note."])
del self.cleaned_data['note']
return self.cleaned_data
正如你所看到的,我有一些if
聲明,確定域是否甚至顯示你的表格(在邏輯上這意味着某些用戶只能修改某些部分的領域)。
我該怎麼做ModelForm
?我明白fields
是一個元組,因此它不能像我在Form
中那樣追加。所以我想做點像
class OrderDetailForm(forms.ModelForm):
class Meta:
model = Order
# fields = ('work_type', 'vendor', 'note') I can't do that since I need to be able to control it. See below.
# Can I control widgets even if that field doesn't exist?
widgets = {
'note': forms.Textarea(),
}
def __init__(
self,
user,
can_edit_work_type=None,
can_edit_vendor=None,
can_edit_note=None,
*args,
**kwargs
):
super(OrderDetailForm, self).__init__(*args, **kwargs)
fields = []
if can_edit_work_type:
fields.append('work_type')
if can_edit_vendor:
fields.append('vendor')
if can_edit_note:
fields.append('note')
self.Meta.fields = tuple(fields) # Does this work?
def clean(self):
super(OrderDetailForm, self).clean()
if 'note' in self.cleaned_data:
if len(self.cleaned_data['note']) < 50:
self._errors['note'] = self.error_class([u"Please enter a longer note."])
del self.cleaned_data['note']
return self.cleaned_data
這可能嗎?如何控制ModelForm
中的字段?
我喜歡儘可能地保留我的請求處理程序,並將邏輯放在'forms','models'和其他地方,而不是處理程序本身。 –
這不會在有效的帖子後返回HttpResponse。 –
這不會將字段添加到表單。 ...或者這樣做......嗯......這有點兒很棒,但是處理程序中嵌套的類只是錯誤的;) –