2010-11-08 70 views
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 

回答

1

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

這是因爲形式沒有現場叫poll因爲your're明確地排除它的形式定義。我無法說清你給的是PollForm還是ChoiceForm,但都沒有poll字段。

+0

正確,但我使用以下代碼設置值。這是做錯了嗎? - 對於cf在cforms: new_choice = cf.save(commit = False) new_choice.poll = new_poll new_choice.save() – jlarry 2010-11-08 20:39:04

+0

是的,但你設置該值後乾淨()已被調用is_valid()並且clean()仍然試圖訪問一個只在表單實例中不存在的字段... – 2010-11-09 08:54:52

+0

沒錯,那麼完成這個的正確方法是什麼?我發現有什麼問題,但還沒有想出一種方法來重寫它以正確工作。 – jlarry 2010-11-09 23:00:51