Django 1.6
I have a working block of code in a Django form class as shown below. The data set from which I\'m building the form field list can include an initial val
I had a similar problem setting the initial value for a radio button called 'needs_response' and solved it by inspecting self's attributes and referencing 'declared_fields':
# views.py
def review_feedback_or_question(request, template, *args, **kwargs):
if 'fqid' in kwargs:
fqid = kwargs['fqid']
submission = FeedbackQuestion.objects.get(pk=fqid)
form = FeedbackQuestionResponseForm(submission_type=submission.submission_type)
# other stuff
# forms.py
class FeedbackQuestionResponseForm(forms.Form):
CHOICES = (('1', 'Yes'), ('2', 'No'))
response_text = forms.CharField(
required=False,
label='',
widget=forms.Textarea(attrs={'placeholder': 'Enter response...'}))
needs_response = forms.ChoiceField(choices=CHOICES,
label='Needs response?',
widget=forms.RadioSelect())
def __init__(self, *args, **kwargs):
if 'submission_type' in kwargs:
submission_type = kwargs.pop('submission_type')
if submission_type == 'question':
self.declared_fields['needs_response'].initial = 1
else:
self.declared_fields['needs_response'].initial = 2
super(FeedbackQuestionResponseForm, self).__init__(*args, **kwargs)