How can I render a ManyToManyField as checkboxes?

前端 未结 3 774
闹比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:34

    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()
    
    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2020-12-23 10:42
    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.

    0 讨论(0)
提交回复
热议问题