使用多个表单验证Django中的对象

时间:2010-11-08 19:33:09

标签: django validation forms

使用this example。假设两种形式都有日期字段。您如何编写自定义清理以进行验证以比较两个日期?我在底部添加了一个示例clean,它在poll上返回一个关键错误。

模型和表格

from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField()
    target_date= models.DataTimeField()

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    target_date= models.DataTimeField()
    votes = models.IntegerField(default=0)
To start, we’ll need forms for each model.

from django import forms
from mysite.polls.models import Poll, Choice

class PollForm(forms.ModelForm):
    class Meta:
        model = Poll

class ChoiceForm(forms.ModelForm):
    class Meta:
        model = Choice
        exclude = ('poll',)

浏览

from mysite.polls.models import Poll, Choice
from mysite.polls.forms import PollForm, ChoiceForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

def add_poll(request):
    if request.method == "POST":
        pform = PollForm(request.POST, instance=Poll())
        cforms = [ChoiceForm(request.POST, prefix=str(x), instance=Choice()) for x in range(0,3)]
        if pform.is_valid() and all([cf.is_valid() for cf in cforms]):
            new_poll = pform.save()
            for cf in cforms:
                new_choice = cf.save(commit=False)
                new_choice.poll = new_poll
                new_choice.save()
            return HttpResponseRedirect('/polls/add/')
    else:
        pform = PollForm(instance=Poll())
        cforms = [ChoiceForm(prefix=str(x), instance=Choice()) for x in range(0,3)]
    return render_to_response('add_poll.html', {'poll_form': pform, 'choice_forms': cforms})

在表单上运行示例clean,返回poll的键错误。

def clean(self):
        if any(self.errors):
            raise forms.ValidationError("")
        data = self.cleaned_data
        choiceDate = data["target_date"]
        pollDate = data["poll"]    ##--- The key error happens here
        if choiceDate > pollDate.target_date:
            raise forms.ValidationError("Your dates do not match")
        return data

1 个答案:

答案 0 :(得分:1)

pollDate = data["poll"] ##--- The key error happens here

那是因为表单没有名为poll的字段,因为您在表单定义中明确地将其排除。我无法告诉您提供的内容是PollForm还是ChoiceForm,但都没有poll字段。