1
使用this example。假设这两种形式都有日期字段。你会如何编写一个自定义清理来验证比较两个日期?我在底部添加了一个干净的例子,它在poll上返回一个关键错误。以多种形式验证Django中的对象
模型,并形成
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})
例干净存在跑返回的关键错误投票的形式。
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
正确,但我使用以下代码设置值。这是做错了吗? - 对于cf在cforms: new_choice = cf.save(commit = False) new_choice.poll = new_poll new_choice.save() – jlarry 2010-11-08 20:39:04
是的,但你设置该值后干净()已被调用is_valid()并且clean()仍然试图访问一个只在表单实例中不存在的字段... – 2010-11-09 08:54:52
没错,那么完成这个的正确方法是什么?我发现有什么问题,但还没有想出一种方法来重写它以正确工作。 – jlarry 2010-11-09 23:00:51