ModelMultipleChoiceField forcing required

91 views
Skip to first unread message

Scot Hacker

unread,
Nov 5, 2014, 2:11:27 PM11/5/14
to django...@googlegroups.com
I'm having a strange issue with a pair of ManyToManyFields, where they're acting like they're required fields in the admin even though they're not.


# In models.py
    instructors = models.ManyToManyField(Instructor, blank=True)
    students
= models.ManyToManyField(Profile, blank=True)



I can update an instance of this model with no instructors or students from the CLI just fine. The fields are not required. But I'm using ModelMultipleChoiceField in the admin:


# In admin.py
class OfferingAdminForm(forms.ModelForm):

    instructors
= forms.ModelMultipleChoiceField(
        widget
= widgets.FilteredSelectMultiple('Instructors',is_stacked=False),
        queryset
= Instructor.objects.all())


    students
= forms.ModelMultipleChoiceField(
        widget
= widgets.FilteredSelectMultiple('Students',is_stacked=False),
        queryset
= User.objects.filter(is_active=True))

and when I try to save via the admin, it tells me these fields are required. If I tweak it to not use this ModelForm, I can save without instructors or students just fine. 

Theories? Thanks.

Carl Meyer

unread,
Nov 5, 2014, 2:15:47 PM11/5/14
to django...@googlegroups.com
Hi Scot,
When you override a field in a ModelForm, you lose the ability for it to
automatically pick up configuration from the model field. Either the
field is auto-created by the ModelForm based on your model field, or it
is created manually by you; it can't be both.

So because you are manually creating your `instructors` and `students`
fields on the form, the `blank=True` in the model has no effect; you
need to pass `required=False` to your two form fields.

(Because of this, I frequently choose to update/tweak form fields in an
overridden `__init__` method of a ModelForm, rather than overriding the
fields entirely.)

Carl

Scot Hacker

unread,
Nov 5, 2014, 2:29:00 PM11/5/14
to django...@googlegroups.com


On Wednesday, November 5, 2014 11:15:47 AM UTC-8, Carl Meyer wrote:



So because you are manually creating your `instructors` and `students`
fields on the form, the `blank=True` in the model has no effect; you
need to pass `required=False` to your two form fields.

Got it, right you are - that works fine. 
 

(Because of this, I frequently choose to update/tweak form fields in an
overridden `__init__` method of a ModelForm, rather than overriding the
fields entirely.)


Makes sense! 

Thanks,
./s
 
Reply all
Reply to author
Forward
0 new messages