Skip to main content

Posts

Showing posts from August, 2020

Checking the right boxes

 A student created a modelform but was struggling with one of the fields. He wanted it to render as checkboxes that would allow the user to select multiple choices. I was surprised that it was actually a little challenging to find any article online that showed one how exactly to do this. Perhaps I wasn't using the right key words in my search? I did figure it out fairly quickly in the end.  models.py class Cats(models.Model):     fav_toys = models.CharField(max_length=100) forms.py TOYS = [     ('Rubberband', 'Rubberband'),     ('Ball', 'Ball'),     ('Feather', 'Feather'), ] class CatForm(ModelForm):     class Meta:         model = Cats         fields = '__all__'         widgets = {             'fav_toys': forms.CheckboxSelectMultiple(choices=TOYS),  } And that did the trick! It's interesting that when the choices were defined in models.py rather than forms.py, it didn't work. I'm not entirely sure as to w