How can I render a ManyToManyField as checkboxes?

前端 未结 3 801
闹比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()
    

提交回复
热议问题