broinjc
broinjc

Reputation: 2699

Change default form widget for choices

I am trying to model a survey.

models.py

class Survey(models.Model):
    Student = models.ForeignKey(Student)

    OPTIONS = (
        ('0','Behavior 1'),
        ('1','Behavior 2'),
        ('2','Behavior 3'),
        )

    behaviors = models.SmallIntegerField(choices=OPTIONS)
    how_cool = models.SmallIntegerField() # rating from 1 to 5

I want to display behaviors as a group of checkboxes, not the default dropdown. Do I need to write a custom model field?

Upvotes: 0

Views: 558

Answers (1)

Serafeim
Serafeim

Reputation: 15084

Create a ModelForm that specifies the behaviors as a checkbox:

from django.forms import ModelForm, CheckboxInput

class SurveyForm(ModelForm):
    behaviors =  forms.ChoiceField(choices=OPTIONS, widget=CheckboxInput)

Now you can use this form in your Admin or CBVs to render the behaviors as a checkbox.

Take also a look here: https://docs.djangoproject.com/en/dev/ref/forms/fields/#widget

Upvotes: 1

Related Questions