Empty results in dynamical form in Django

Question:

My views.py:

from django.shortcuts import render
from django.shortcuts import HttpResponse
from .models import *
from .forms import TestForm
from django import forms
def TestView(request,id):
    test = Tests.objects.get(id=id)
    queshions = Queshions.objects.filter(test=test)
    form = TestForm(queshions=queshions)
    if request.method == 'POST':
        print(request.POST)
        form = TestForm(data=request.POST, queshions=queshions)
        print(form)
        print(form.is_valid())
    else:
        context = {'queshions':queshions,'test': test,'form':form }
        return render(request,'testview.html',context)

My forms.py:

from django import forms


class TestForm(forms.Form):
  def __init__(self, *args, **kwargs):
    queshions = kwargs.pop('queshions')
    super(TestForm, self).__init__(*args, **kwargs)
    for queshion in queshions:
        self.fields[queshion.id] = forms.CharField(label=queshion.text)

POST request is correct, but form.is_valid returns False, and when i am printing form it writes
"This field is required." like it is empty

Answers:

Field names should be strings:

# self.fields[queshion.id] = forms.CharField(label=queshion.text)     # Change this
self.fields[str(queshion.id)] = forms.CharField(label=queshion.text)  # to this

The keys in request.POST are strings:

form = TestForm(data=request.POST, queshions=queshions)
Answered By: aaron
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.