Reputation: 3574
I have the following form:
class TutorForm(SignupForm):
subjects = forms.ModelMultipleChoiceField(queryset=Subject.objects.all(),
widget=forms.CheckboxSelectMultiple())
I have a child form called TutorUpdateForm
that 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
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