Reputation: 9532
I have a FormView
with a ModelForm
to create a particular model.
Now let's say I want to be able to edit that model, but only a subset of fields, so only these can be modified and validation will be run only on these, and not the others (and the others won't appear as "required", etc).
Is it possible to reuse the existing ModelForm
in this scenario, or do I have to create a new form altogether?
Upvotes: 0
Views: 58
Reputation: 8250
You can pass some sort of "flag" to let the form know which fields to treat differently.
A code example will make more sense:
# your view
class SpecialFormView(FormView):
# [...your view attributes..]
def get_form_kwargs(self):
kwargs = super(SpecialFormView, self).get_form_kwargs()
kwargs['is_special'] = True
return kwargs
# your form
class MyModelForm(ModelForm):
# [... your fields and meta..]
def __init__(self, *args, **kwargs):
is_special = kwargs.pop('is_special', False)
super(MyModelForm, self).__init__(*args, **kwargs)
if is_special:
for field in ['field_1', 'field_2']:
self.fields[field].required = False
Upvotes: 1