Asterisk
Asterisk

Reputation: 3574

django render initial values in form with ModelMultipleChoiceField and CheckboxSelectMultiple() widget

I have the following form:

class TutorForm(SignupForm):
   subjects = forms.ModelMultipleChoiceField(queryset=Subject.objects.all(),
                                          widget=forms.CheckboxSelectMultiple())

I have a child form called TutorUpdateFormthat inherits from TutorForm and it sets initial values in init method.

self.fields['subjects'].initial = current_user.subjects.all()

In my template however the values are not checked (in views the values are there, so setting initial values works). How can I enforce checked inputs in the template?

EDIT (init code)

def __init__(self, *args, **kwargs):
    current_user = None
    try:
        current_user = kwargs.pop('user')
    except Exception:
        pass
    super(TutorUpdateForm, self).__init__(*args, **kwargs)

    for field in _update_exclude:
        self.fields.pop(field)

    if current_user:
        self.fields['subjects'].initial = current_user.subjects.all()

Upvotes: 2

Views: 3192

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32244

You should pass the initial values into the call to super, you can also set a default value for dict.pop rather than using try/except

def __init__(self, *args, **kwargs):
    current_user = kwargs.pop('user', None)

    initial = kwargs.get('initial', {})
    if current_user:
        initial.update({'subjects': current_user.subjects.all()})
    kwargs['initial'] = initial

    super(TutorUpdateForm, self).__init__(*args, **kwargs)

    for field in _update_exclude:
        self.fields.pop(field)

Here is a link to the documentation on dynamic initial values for forms

Upvotes: 5

Related Questions