2012-11-19 63 views
0

使用Django和模型表單集Im。它是一個多選題的非常基本的模型。成功創建問題的表單使用模型表單集和常規表單 - 問題的常規表單和可能的答案的表單集。這部分工作。將數據綁定到django模型表單集

但是,如何創建一個'編輯'版本呢?我想查詢當前爲給定問題保存的答案,並將這些答案綁定到formset中的每個表單。

謝謝,邁克

型號:

class Question(models.Model): 
    title = models.CharField(...) 
    text = models.TextField(...) 
    time_allowed = models.DecimalField(...) 

class Answer(models.Model): 
    uuid = models.CharField(...) 
    question = models.ForeignKey(QuestionDetail, ...) 
    text = models.TextField() 
    weight = models.DecimalField(...) 

的形式:

class QuestionModelForm(forms.ModelForm): 
    required_css_class = 'required' 
    class Meta: 
    model = QuestionDetail 
    widgets = { 
     'text': forms.Textarea(attrs={'rows': 3, 'class': 'question-text'}) 
    }  

class AnswerModelForm(forms.ModelForm): 
    required_css_class = 'required' 
    class Meta: 
    widgets = { 
     'text': forms.Textarea(attrs={'rows': '3', 'class': 'question-text'}), 
     'weight': forms.TextInput(attrs={'maxlength':'5', 'class': 'question-weight'}), 
    }  

class BaseAnswerFormSet(BaseFormSet): 
    def __init__(self, *args, **kwargs): 
    super(BaseAnswerFormSet, self).__init__(*args, **kwargs) 
    # Must have at least two answers. 
    self.forms[0].empty_permitted = False 
    self.forms[1].empty_permitted = False  

AnswerFormSet = modelformset_factory(Answer, formset=BaseAnswerFormSet, form=AnswerModelForm) 

回答

1

嘗試queryset關鍵字參數:

answers_qs = my_question.answer_set 
AnswerFormSet = modelformset_factory(Answer, 
            formset=BaseAnswerFormSet, 
            form=AnswerModelForm, 
            queryset=answers_qs)