I’m using Django 4.0 and I’m trying to create a web app where the user selects a choice from a dropdown Django form. However, the choices will vary depending on the question and I want the form to be able to adapt to this.
This is what I have in forms.py:
class QuestionAnswerForm(forms.Form):
def __init__(self, q_id, *args, **kwargs):
self.q_id = q_id
super(QuestionAnswerForm, self).__init__(*args, **kwargs)
q_id = self.q_id # this line throws an error
question = Question.objects.get(pk=q_id)
choice = forms.ChoiceField(choices=get_choices(question))
However, I get the error: name ‘self’ not defined. I just want to know an easy way to pass the question id to the form so that the get_choices function can then return the choices that need to be displayed on the form.
In views.py, the start of my view for the question sets the form in this way:
def question_detail_view(request, q_id):
print(f"Question id is {q_id}")
form = QuestionAnswerForm(request.POST or None, q_id=q_id)