使用ModelForm,模型包含我应该在表单中呈现的字段的值:
class MyClass(models.Model):
my_field = models.CharField(max_length=256) # this contains the type of the form's field for example a CharField or a DateTimeField
我的观点:
class MyView(FormView):
form_class = CustomForm
model = MyClass
表单类:
class MyForm(forms.ModelForm):
class Meta:
model = MyClass
fields = ?
如何动态设置表单的字段类型?
答案 0 :(得分:2)
我会列出fields = ()
中您可能需要的所有可能字段,然后您可以删除不需要的字段,根据需要更改字段等,根据模型字段的值,如下所示;
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
if self.instance:
if self.instance.my_field == 'value':
del self.fields['my_field'] # remove 'my_field'
self.fields['name'].required = False # change required value
class Meta:
model = MyClass
fields = (
'name',
'address',
'my_field',
'some_other_field'
)
因此,从您的角度来看,如果您希望获得表单的值,您可以执行类似的操作;
my_object = MyClass.objects.first()
form = MyForm(instance=my_object)
context['form'] = form
# etc, etc
然后你可以像我上面建议的那样从该对象的字段中获取值。
如果需要,你也可以将任意args / kwargs传递给你的表单(假设你实际上没有一个对象来检查值,而是想根据其他数据传递一些东西;
# in a view;
form = MyForm(my_var='something')
# in the form;
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
my_var = kwargs.pop('my_var')
super(MyForm, self).__init__(*args, **kwargs)
if my_var == 'value':
del self.fields['my_field'] # remove 'my_field'