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',)
checkbox django django-forms many-to-many modelform
Rob
source share