Django model form using forms.ModelMultipleChoiceField

I have a ModelForm in my Django application that uses form.ModelMultipleChoiceField, which displays as widget.CheckboxSelectMultiple on the form. This ModelForm is used to select / deselect many-to-many relationships. Here's the problem: when you uncheck all the boxes and save the form, it is not saved. If you uncheck all but 1, it really is saved.

Are there any tricks I miss here about model forms and many-to-many relationships? Am I encountering a mistake? I am new to Django. Thanks in advance.

Custom field:

class NetworkMessageChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return obj.display_message 

Model Shape:

 class MessageTemplateForm(forms.ModelForm): network_messages = NetworkMessageChoiceField(queryset=NetworkMessageTemplate.objects, widget=forms.CheckboxSelectMultiple()) class Meta: model = UserProfile fields = ('network_messages',) 

A view that retains its shape:

 def save_message_templates(request, extra_context=dict()): try: profile_obj = request.user.get_profile() except ObjectDoesNotExist: profile_obj = UserProfile(user=request.user) if request.method == 'POST': form = MessageTemplateForm(request.POST, instance=profile_obj) if form.is_valid(): form.save() return redirect('/') return index(request, message_template_form=form) 

Edit:

The field of my form was missing. Required = False.

 class MessageTemplateForm(forms.ModelForm): network_messages = NetworkMessageChoiceField(queryset=NetworkMessageTemplate.objects, widget=forms.CheckboxSelectMultiple(), required=False) class Meta: model = UserProfile fields = ('network_messages',) 
+6
checkbox django django-forms many-to-many modelform
source share
1 answer

You do not insert what looks in your model, so I assume that the network_messages field in your model is not required. If so, then when you try to submit a form with the value of this field as NULL (empty), form.is_valid() does not return True , and therefore your form.save() will never be executed.

Have you tried to execute this material from an interactive shell, creating an instance of the form and trying to manually save() it?

0
source share

All Articles