Django Multiple Choice Field / Checkbox Select Multiple

前端 未结 6 1172
清酒与你
清酒与你 2020-11-29 18:09

I have a Django application and want to display multiple choice checkboxes in a user\'s profile. They will then be able to select multiple items.

This is a simplifi

6条回答
  •  日久生厌
    2020-11-29 19:04

    Brant's solution is absolutely correct, but I needed to modify it to make it work with multiple select checkboxes and commit=false. Here is my solution:

    models.py

    class Choices(models.Model):
        description = models.CharField(max_length=300)
    
    class Profile(models.Model):
       user = models.ForeignKey(User, blank=True, unique=True, verbose_name_('user'))
       the_choices = models.ManyToManyField(Choices)
    

    forms.py

    class ProfileForm(forms.ModelForm):
        the_choices = forms.ModelMultipleChoiceField(queryset=Choices.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)
    
        class Meta:
            model = Profile
            exclude = ['user']
    

    views.py

    if request.method=='POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            profile = form.save(commit=False)
            profile.user = request.user
            profile.save()
            form.save_m2m() # needed since using commit=False
        else:
            form = ProfileForm()
    
    return render_to_response(template_name, {"profile_form": form}, context_instance=RequestContext(request))
    

提交回复
热议问题