2

Lets say I have the following model

class Application(models.Model):
    occupation = models.TextField()

and form

class ApplicationForm(forms.ModelForm):
    def __init__(self, *args, **kwargs)
        super().__init__(*args, **kwargs)
        self.fields['occupation'] = forms.MultipleChoiceField(choices=OCCUPATION_CHOICES, widget=CheckboxSelectMultiple)

    class Meta:
        model = Application

When I use it with a instance (for example via admin) the choices are not selected.

What am I doing wrong?

Edit: Clarification: When I select some choices, I hit submit it saves the data. They look like ['undergraduate', 'postdoc'] in the database. But they are not checked in the form anymore.

Zoli
  • 831
  • 1
  • 11
  • 27

2 Answers2

4

I managed to get it working like this.

import ast
class ApplicationForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        if kwargs.get('instance'):
            kwargs['initial'] = {
                'occupation': ast.literal_eval(kwargs.get('instance').occupation or '[]'),
            }
        super().__init__(*args, **kwargs)

    class Meta:
        model = Application
        widgets = {
            'occupation': CheckboxSelectMultiple(choices=OCCUPATION_CHOICES),
        }

Thanks go to RodrigoDela who made me realize what I was doing wrong and pointed me in the right direction.

Zoli
  • 831
  • 1
  • 11
  • 27
1

Edit: A TextField cannot store multiple choices. Take a look at this: Django Model MultipleChoice

Either you use this, or you override your forms, so that these can parse the instance.occupation content into their form.occupation field.

Community
  • 1
  • 1
RodrigoDela
  • 1,706
  • 12
  • 26