[Answer]-Django model form โ€“ Exclude a field that has no model field

1๐Ÿ‘

โœ…

You could subclass the form and add the extra field in the subclass:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel

class MyUpdateModelForm(MyModelForm):
    update_values = forms.BooleanField(required=False) #this field has no model field

    class Meta:
        model = MyModel

You can then override the get_form method of your admin, which is passed the current instance: get_form(self, request, obj=None, **kwargs)

๐Ÿ‘คsk1p

0๐Ÿ‘

Rather than removing the field in __init__ if instance.pk is not None, how about adding it if it is None? Remove the class-level declaration and just change the logic:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.pk is not None:
            self.fields['update_values'] = forms.BooleanField(required=False) 
๐Ÿ‘คDaniel Roseman

Leave a comment