How can I render a ManyToManyField as checkboxes?

前端 未结 3 794
闹比i
闹比i 2020-12-23 10:17

I\'m making a game link site, where users can post links to their favorite web game. When people post games they are supposed to check what category the game falls into.

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-23 10:38

    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!

提交回复
热议问题