Inline formset factory ignores 'exclude=' for foreign key field

694 views
Skip to first unread message

gulrtosk

unread,
Mar 1, 2012, 11:24:45 AM3/1/12
to django...@googlegroups.com
Hello list,

through trial and error I discovered that it isn't required to pass the foreign key form field post data to the constructor of an inline form set. Django will fill it in automatically by looking at the primary key of the 'instance=' given. So I figured I might as well exclude the hidden FK field from the form:

class Group(models.Model):
    interest = models.CharField(max_length=100)
class Member(models.Model):
    name = models.CharField(max_length=100)
    group = models.ForeignKey(Group)

MemberFormSet = inlineformset_factory(Group, Member, exclude=('group',))

The 'exclude=' instruction is ignored and the form is printed the same as without 'exclude=('group',)'. This is odd, since the FKs aren't strictly required in the form set: if you pass post data *with* foreign key fields to the constructor MemberFormSet(), Django will use it for validation, but if you don't pass them, it's fine too, because Django will simply use the instance to fill them in automatically.

So, how can I exclude my 'group' foreign keys from the printed form set?

Thank you and cheers, glts

gulrtosk

unread,
Mar 1, 2012, 5:07:24 PM3/1/12
to django...@googlegroups.com
Right, I don't know whether this is a bug or done on purpose ... It looks like it was done on purpose so I'd be happy to hear the experts on this. I'm using Django 1.3. I hope I got this right.

On line 752 of django.forms.models (development trunk), in the add_fields() method of BaseInlineFormSet it says:

name = self.fk.name
...
form.fields[name] = InlineForeignKeyField(self.instance, **kwargs)

This is *after* all processing of 'fields=' and 'exclude=' kwargs has been done on the form. Consequently, for all inline form sets the foreign key field is always included. It is not possible to 'exclude=' it. Any opinions on why this should be so?
Reply all
Reply to author
Forward
0 new messages