Question

I would like to set up a form based on the values I have stored in my database.

Let's say I have some models like this:

class Questions(models.Model):
    question = models.CharField(max_length=350)

class Answers(models.Model):
    question = models.ForeignKey(Questions)
    answer = models.CharField(max_length=350)

And I would like to create a form in this way:

for x in Questions:
   answer = forms.CharField(label = x.question)

And thereby having exactly the number of answer fields in the form as there are questions stored in the database. Any ideas?

Was it helpful?

Solution

This is the solution I came up with. Seems to work okay, but I feel like there is a cleaner solution I am missing.

in my forms.py:

class AnswerForm(forms.Form):
    def __init__(self, *args, **kwargs):
         super(AnswerForm, self).__init__(*args, **kwargs)

         for x in Questions.objects.all():
         self.fields[x.question] = ModelChoiceField(queryset=.....
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top