Django - 如何通过迭代数据库查询来创建表单字段?

时间:2014-04-24 22:14:25

标签: django forms django-models django-forms django-views

所以我想根据我存储在数据库中的值设置一个表单。

我们说我有这样的模型:

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

我想以这种方式创建一个表单:

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

因此,在数据库中存储有问题时,表格中的答案字段数确切。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

使用foreignkey创建一个中间表,该表将问题分组并为中间人创建内联formset:

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)

答案 1 :(得分:0)

您可以尝试这样:

**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()