开发者

Validating objects in Django with multiple forms

Using this example. Pretend there are date fields in both forms. How would you write a custom clean for validation to compare both dates? I have added an example clean at the bottom which returns a key error on poll.

models and forms

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',)

Views

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})

Example clean being ran on the form which returns the key error for 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")
        r开发者_JAVA百科eturn data


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

That's because the form has no field called poll because your're explicitly excluding it in the form definition. I can't tell the clean you give is on the PollForm or the ChoiceForm, but neither has a poll field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜