简体   繁体   中英

Django - How to create form fields by iterating through a database query?

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

Let's say I have a model like this:

class Questions(models.Model):
    question = 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?

Use a foreignkey to make an intermediary table that groups the questions and create a inline formset for the intermediary:

class Quiz(models.Model):
    question = models.CharField(max_length=50)

class Question(models.Model):
    quiz = models.ForeignKey(Quiz)
    question = models.CharField(max_length=350)

quiz = Quiz.objects.get(id=1)

QuestionFormSet = inlineformset_factory(Quiz, Question)
formset = QuestionFormSet(instance=quiz)

You can try like this:

**form.py**

class QuestionsForm(forms.Form):
    question = forms.ChoiceField(max_length=100)
    answer= forms.CharField(max_length= 255, widget=forms.Textarea)

def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=None,
                 empty_permitted=False): #import Errorlist
        super(QuestionsForm, self).__init__(data, files, auto_id, prefix, initial, error_class,
                                       label_suffix, empty_permitted)
        self.fields['question'].choices = for x.question in Questions.objects.all()

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