[Fixed]-Why does my excluded field still appear in this Django form?

17👍

exclude needs a tuple, so you need

# note the extra comma
exclude = ('created_by',)

django iterates through the exclude, and since strings are iterable (return each character) this doesn’t throw an error

👤second

3👍

For older Django versions, there’s a problem with excluding non-model fields that you explicitly declare, e.g. in a parent form class. Adding the following in your form’s init will take care of it even for non-model fields (see https://code.djangoproject.com/ticket/8620).

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    [self.fields.pop(f) for f in self.fields.keys() if f in self.Meta.exclude]

0👍

I know this is old but posting here as a reference.

I encountered this same issue because I overloaded clean_fields() on the model, but didn’t call the superclass correctly.

 class MyModel(models.Model):
    foo = models.BooleanField()    

    # Wrong!  Don't do this!
    def clean_fields(self, exclude=None):
        # Bah!  Forgetting to pass exclude defaults it to None!
        super(MyModel, self).clean_fields()
        if not self.foo:
            raise ValidationError('Ah fooey.')

    # Correct!  Do it this way!
    def clean_fields(self, exclude=None):
        # That's better!  Let's take a coffee break.  I'm tired.
        super(MyModel, self).clean_fields(exclude)
        if not self.foo:
            raise ValidationError('Ah fooey.')

Leave a comment