1👍
✅
Well, as @Anentropic mentioned, I was not on the right way.
And he is right, because I need to submit only answer A or B. But for user on the form I need to display text for these answers from Test model. So I wrote two templatetags for this.
class TestForm(forms.ModelForm):
class Meta:
model = TestAnswer
fields = '__all__'
def communicative_test(request):
questions = TestModel.objects.all()
QuestionFormSet = formset_factory(form=TestForm, max_num=questions.count())
formset = QuestionFormSet(initial=[{'candidate': request.user, 'question': x.number} for x in questions])
return render(request, 'testing/communicative.html', locals())
Two custom templatetags for each answer (A/B):
@register.filter(name='get_answer1')
def get_answer1(question):
try:
question = TestModel.objects.get(number=question)
answer = question.answer_1
except ObjectDoesNotExist:
answer = ''
return answer
@register.filter(name='get_answer2')
def get_answer2(question):
try:
question = TestModel.objects.get(number=question)
answer = question.answer_2
except ObjectDoesNotExist:
answer = ''
return answer
And template is:
{% load test_tags %}
<form id="communicative-test-form" method="post">
{% csrf_token %}
{{ question_formset.management_form }}
{% for form in question_formset.forms %}
{% crispy form %}
{{ form.id }}
<p>{{ form.question.value }}</p>
<p><label>
<input type=radio name="form-{{ form.question.value|add:"-1" }}-answer" id='id_form-{{ form.question.value|add:"-1" }}-answer' value="1">
{{ form.question.value|get_answer1 }}
</label></p>
<p><label>
<input type=radio name="form-{{ form.question.value|add:"-1" }}-answer" id='id_form-{{ form.question.value|add:"-1" }}-answer' value="2">
{{ form.question.value|get_answer2 }}
</label></p>
{% endfor %}
<div style="text-align: right;" class="col-md-12">
<button type="submit">Save</button>
</div>
</form>
Source:stackexchange.com