NickP
NickP

Reputation: 1414

Django Multiple Form as dynamic checkboxes

Hoping there is a quick slick Django-esque solution to the following challenge that doesn't involve JavaScript.

Currently, I have a form created that shows a Many to Many field as a simple multiple (the built in behaviour in Django) utalising the following:

Forms.py:

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        exclude = ['email_address']

Template:

<form  method="post">{% csrf_token %}
    {{form}}            
    <button class="btn" type="submit">submit</button>
</form>

Model:

class Profile(models.Model):

    email_address = models.CharField(max_length = 100)

    subscriptions = models.ManyToManyField(Item, blank=True, null=True)

However, to ease the experience for the user (and improve mobile performance) I would like to instead show a list with checkboxes next to each.

Is there an easy way to achieve this without either JavaScript or manually setting each option in the forms.py?

Upvotes: 0

Views: 893

Answers (1)

Saket Patel
Saket Patel

Reputation: 423

Much easier way would be to provide the widget for subscriptions in Meta class of ProfileForm

class Meta:
    model = Profile
    exclude = ['email_address']
    widgets = {
        'subscriptions': forms.CheckboxSelectMultiple,
    }

Upvotes: 3

Related Questions