如何为具有相同名称的多个字段定义ModelForm?

时间:2017-01-06 00:39:15

标签: django django-forms

我想定义一个ModelForm to validate a form which have several choice`字段,如下所示:

<form role="form" action="/create/poll" method="post">
{% csrf_token %}
    <input type="text" name="title">  
    <input type="text" name="choice" ><br>
    <input type="text" name="choice" ><br> 
    <input type="text" name="choice" ><br>

 <button type="submit">Submit</button>
</form>

由于PollChoice是不同的模型,我将两个ModelForms定义为:

class PollForm(forms.ModelForm):
    class Meta:
            model= Poll 
            fields= ('title',)  

class ChoiceForm(forms.ModelForm):
    class Meta:
            model= Choice 
            fields= ('choice',)  

观点:

def create_poll(request):
    form = PollForm()

    args = {}
    if request.method == 'POST':
        print request.POST
        pform = PollForm(request.POST)
        cform = ChoiceForm(request.POST)
        if pform.is_valid():
            poll = pform.save(commit = False)
            poll.title = pform.cleaned_data['title']
            poll.creator = request.user            
            poll.pub_date = timezone.now()
            poll.save()

            if cform.is_valid(): #This condition not met
                for c in cform: 
                    if c != "":
                        choice = cform.save(commit = False)
                        choice.poll = poll.id
                        choice.choice = cform.cleaned_data['c']
                        choice.save()

问题在于未保存选项,因为未验证ChoiceForm

我该如何解决这个问题?

0 个答案:

没有答案