How can I render a ManyToManyField as checkboxes?

Here is how I solved it (Edit: and the admin thing)

Forms:

cats = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Category.objects.all())

(It was the queryset part I couldn't find..)

View:

cats = form.cleaned_data['cats']
    game.cats = cats

And that's all the code needed to save the data.

Edit: here is a solution for the admin

Models:

from django.contrib import admin
from django.forms import CheckboxSelectMultiple

class MyModelAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.ManyToManyField: {'widget': CheckboxSelectMultiple},
    }

Admin:

from gamesite.games.models import Game, MyModelAdmin

admin.site.register(Game, MyModelAdmin)

It's kind of quirky in looks, but works! If someone finds a way to make it more "clean" please post!

Cheers!


class GameForm(forms.ModelForm): 
        name = forms.CharField(max_length=15, label='Name') 
        url = forms.URLField(label='URL', initial='http://') 
        cats = forms.ModelMultipleChoiceField(
            queryset=Category.objects.all(),
            widget=forms.CheckboxSelectMultiple,
            required=True)

        class Meta: 
                model = Game 
                fields = ('name','url','cats')

that should fix your view, but i'm not sure about the admin. still looking... will edit if i find anything.


Found this on from Chase Seibert, Engineering Manager of Dropbox

Source from Chase Seibert

from django.db import models
from django.forms.models import ModelForm
from django.forms.widgets import CheckboxSelectMultiple

class Company(models.Model):  
    industries = models.ManyToManyField(Industry, blank=True, null=True)

class CompanyForm(ModelForm):

    class Meta:
        model = Company
        fields = ("industries")

    def __init__(self, *args, **kwargs):

        super(CompanyForm, self).__init__(*args, **kwargs)

        self.fields["industries"].widget = CheckboxSelectMultiple()
        self.fields["industries"].queryset = Industry.objects.all()

Tags:

Python

Django