is it possible to create an extra field on a form only when the form is adding an entry and not editing one. I gu开发者_Go百科ess this would be something on the init function with a check on whether instance had been set or not. Currently my form looks like this
class AreaForm(forms.ModelForm):
any_locations = forms.BooleanField(label="Does this area have any locations?",
initial=True,
required=False)
class Meta:
model = Area
but I only want the any_locations
field there when I'm adding an entry and not editing it. I guess I could have 2 forms but wondered if there was a neater way?
You should be able to check if the form has an instance. If not add in the extra field
def __init__(self, *args, **kwargs):
super(AreaForm, self).__init__(*args, **kwargs)
if 'instance' not in kwargs:
self.fields['any_locations'] = forms.BooleanField(label="Does this area have any locations?", initial=True, required=False)
精彩评论