这是我的forms.py:
class MatchingForm(forms.Form):
def __init__(self, *args, **kwargs):
super(MatchingForm, self).__init__(*args, **kwargs)
for matchq in MatchQuestions.objects.all():
self.fields[matchq.question] = forms.ModelChoiceField(queryset=Choice.objects.filter(question=matchq.id))
self.fields[matchq.howImportant] = forms.ChoiceField(choices=((1,"Very Important"),(2,"Not Important"),))
如您所见,此表单遍历数据库中的数据。如何在我的视图中迭代这些动态表单字段,以便将每个字段保存到每个字段中?谢谢
答案 0 :(得分:0)
基本思想是覆盖表单的save方法,并迭代cleaning_data
class MatchingForm(forms.Form):
[...]
def save(self):
for question, howImportant in self.cleaned_data.items():
obj, created = MatchQuestions.objects.get_or_create(question=question,
howImportant=howImportant)
PD:这是一个例子,因为我不了解您的数据模型。