开发者

django forms add extra field only on add

开发者 https://www.devze.com 2023-02-12 22:30 出处:网络
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 in

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号