簡體   English   中英

您如何保存此表單數據?

[英]How do you save this form data?

這是我的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"),))

如您所見,此表單遍歷數據庫中的數據。 如何在我的視圖中遍歷這些動態表單字段,以便將它們保存到每個表單中? 謝謝

基本思想是覆蓋表單的save方法,並迭代cleaned_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:這是一個示例,因為我不知道您的數據模型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM