# How can I set a field value in templates?

**URL:** <https://forum.djangoproject.com/t/how-can-i-set-a-field-value-in-templates/17668>\
**Category:** Forms & APIs\
**Created:** [December 17, 2022, 1:08pm UTC](https://forum.djangoproject.com/t/how-can-i-set-a-field-value-in-templates/17668 "2022-12-17T13:08:12Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Yes](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/yes/32/10610_2.png) [@Yes](https://forum.djangoproject.com/u/Yes)\
**Post date:** [December 17, 2022, 1:08pm UTC](https://forum.djangoproject.com/t/how-can-i-set-a-field-value-in-templates/17668/1 "2022-12-17T13:08:12Z")

</div>

I’m trying to write a form for a basic multiple choice quiz. I’ve tried writing the form manually on my template and it’s fine but I would like to use a django form instead. I’m trying to assign the options for the form on my template but I can’t seem to find the correct way of doing this anywhere so I’d appreciate some help

models.py

```auto
class Quiz(models.Model):
    quiz_id = models.AutoField(primary_key=True)
    quiz_name = models.TextField()

class QuizQuestion(models.Model):
    question_id = models.AutoField(primary_key=True)
    question_text = models.TextField()
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)

class QuestionOption(models.Model):
    option_id = models.AutoField(primary_key=True)
    option_text = models.TextField()
    is_correct = models.BooleanField()
    question = models.ForeignKey(QuizQuestion, on_delete=models.CASCADE)

```

forms.py

```auto
class QuizForm(forms.Form):
    fields = ['options']

```

template (form written manually)

```auto
<div class="container">
        <form method="POST" class="mt-2">
            {% for question in all_questions %}
                </br>
                {{ question.question_text }}
                {% for option in question.questionoption_set.all %}
                    </br>
                    <input type="radio" id="option_{{option.option_id}}" value="{{option.option_text}}">
                    <label for="option_{{option.option_id}}">{{option.option_text}}</label>
                {% endfor %}
            {% endfor %}
            <center><button class="btn btn-custom mt-2" type="submit">SUBMIT</button></center>
        </form>
    </div>

```

I’ve tried using:

```auto
{% for option in question.questionoption_set.all %}
      </br>
      {{ quizform }}
      {{ quizform.options(value=option.option_text) }}
{% endfor %}

```

but I got a TemplateSyntaxError

So in short, I would like to know what the correct syntax would be / the correct way of writing this form

Thanks in advance :))

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 17, 2022, 3:59pm UTC](https://forum.djangoproject.com/t/how-can-i-set-a-field-value-in-templates/17668/2 "2022-12-17T15:59:11Z")

</div>

What you are looking for is a [`ChoiceField`](https://docs.djangoproject.com/en/4.1/ref/forms/fields/#choicefield) for your questions. You can then define a function to return the set of [choices](https://docs.djangoproject.com/en/4.1/ref/forms/fields/#django.forms.ChoiceField.choices) to be used for each question.

Also, since you are rendering multiple instances of essentials the same form, you want to build this page using a [formset.](https://docs.djangoproject.com/en/4.1/topics/forms/formsets/#formsets)

---

<div class="post-metadata">

**Author:** ![Yes](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/yes/32/10610_2.png) [@Yes](https://forum.djangoproject.com/u/Yes)\
**Post date:** [December 17, 2022, 5:06pm UTC](https://forum.djangoproject.com/t/how-can-i-set-a-field-value-in-templates/17668/3 "2022-12-17T17:06:44Z")

</div>

I’ve tried using formsets as you advised, but I’m getting a KeyError.

views.py

```auto
def quiz_ongoing(request, quiz_id):
    chosenquiz_id = quiz_id
    all_questions = QuizQuestion.objects.filter(quiz_id=chosenquiz_id)
    for question in all_questions:
        curr_question = question.question_id
        option = QuestionOption.objects.filter(question_id=curr_question).values_list('option_text', flat=True)
        quizform = QuizForm(options=option)
QuizFormSet = formset_factory(QuizForm)
quizformset = QuizFormSet()
return render(request, 'quiz_ongoing.html', {'quizformset': quizformset})

```

forms.py

```auto
class QuizForm(forms.Form):
    options = forms.MultipleChoiceField()

    def __init__ (self, *args, **kwargs):
        options = kwargs.pop('options')
        super(QuizForm, self). __init__ (*args, **kwargs)
        self.fields['options'] = forms.MultipleChoiceField(choices = [(o, str(o)) for o in options], widget=RadioSelect)

```

template

```auto
    <div class="container">
        <form method="POST" class="mt-2">
            {% csrf_token %}
            {{ quizformset.management_form }}
            {% for form in quizformset %}
                {{ form }}
            {% endfor %}
            <center><button class="btn btn-custom mt-2" type="submit">SUBMIT</button></center>
        </form>
    </div>

```

The error:  
KeyError  
Error during template rendering  
Exception Type: KeyError at /assignments/quiz\_ongoing/2  
Exception Value: ‘options’

Thanks again

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 17, 2022, 5:40pm UTC](https://forum.djangoproject.com/t/how-can-i-set-a-field-value-in-templates/17668/4 "2022-12-17T17:40:30Z")

</div>

None of this:

> [@Yes](#):
>
> ```auto
> for question in all_questions:
> curr_question = question.question_id
> option = QuestionOption.objects.filter(question_id=curr_question).values_list('option_text', flat=True)
> quizform = QuizForm(options=option)
> 
> ```

does you any good and can all be deleted.

(Side note - I’m hoping this is a copy/paste error, but these lines:

> [@Yes](#):
>
> ```auto
> QuizFormSet = formset_factory(QuizForm)
> quizformset = QuizFormSet()
> return render(request, 'quiz_ongoing.html', {'quizformset': quizformset})
> 
> ```

don’t show up as being indented in your view. If they’re not indented as part of your view, that is a mistake.)

The purpose of the formset is to allow the formset to generate the individual forms, including the construction of any specialization that may be necessary.

In the section for `QuizForm`, I would recommend changing one of these variables named “options” to something else, just to avoid confusion. (Your “You in six months” will appreciate it.)

For actually creating “dynamic options” for forms, I suggest you read:

- [Passing custom parameters to formset forms](https://docs.djangoproject.com/en/3.1/topics/forms/formsets/#passing-custom-parameters-to-formset-forms)
- [Pass different parameters to each form in formset](https://forum.djangoproject.com/t/pass-different-parameters-to-each-form-in-formset/4040)
- [Django formsets tutorial series: Foundations](https://datalowe.com/post/formsets-tutorial-1/).

And you may also want to read the thread at [Forms fields based on database content](https://forum.djangoproject.com/t/forms-fields-based-on-database-content/8317)
