简体   繁体   中英

How do you pass data into a Django form?

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)

My question is: how do I access the q_id in the QuestionAnswerForm class?

I found out how to do it using Passing **kwargs to Django Form :

forms.py:

class QuestionAnswerForm(forms.Form):

    def __init__(self, *args, **kwargs):
        q_id = kwargs.pop('q_id')
        super(QuestionAnswerForm, self).__init__(*args, **kwargs)

        if q_id:
            self.fields['choice'].choices = get_choices(Question.objects.get(pk=q_id))

    choice = forms.ChoiceField()

views.py:

def question_detail_view(request, q_id):
    form = QuestionAnswerForm(request.POST or None, q_id=q_id)

I believe one solution to this is that when creating your models:

  1. Create question model
  2. Create choice model and link it to a particular question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM