Django验证formset中的字段与另一个同时处理的表单

时间:2010-11-05 20:39:52

标签: django validation formsets

这个可能有点复杂,或者我只是困惑

我在一个页面上有两个表单。一个是表单,另一个是表单。我的目标是根据表单中的字段验证formset中的字段。我对当前正在发生的事情的猜测是,我将Project表单ID传递给formset的方法发生的方式是它没有被选中用于表单集验证。

错误
if target > project.target_date:

异常值:'NoneType'对象没有属性'target_date'

目前无需验证的代码:注意,我正在设置项目以在Milestones模型上允许null。我希望它不允许null,但这是我能弄清楚如何将project_id传递给里程碑表单的唯一方法。

View.py

def ProjectAdd(request): #Finish the template
    qs = Project.objects.none()
    if request.method == 'POST':
        form = ProjectAddForm(request.POST)
        formset = MilestoneFormSet(request.POST)
        if form.is_valid() and formset.is_valid():
            project = form.save()
            instances = formset.save(commit=False)
            for instance in instances:
                instance.project_id = project.id
                instance.save()
            return HttpResponseRedirect(reverse('project.views.detail', args=(project.id,)))
    else:
        form = ProjectAddForm()
        formset = MilestoneFormSet(queryset=qs)
    return render_to_response('project/addProjectForm.html', {
        'form': form,
        'formset': formset,
        'current_date': current_date,
    }, context_instance=RequestContext(request))

Models.py

class Milestone(models.Model):
    project = models.ForeignKey(Project, blank=True, null=True)
    target_date = models.DateField('Target Date')

forms.py

MilestoneFormSet = modelformset_factory(Milestone, extra=1, max_num=50)

我想要使用验证的代码。现在除了forms.py:

之外,一切都是一样的

forms.py

class MilestoneForm(forms.ModelForm):

    def clean(self):
        if any(self.errors):
            raise forms.ValidationError("")
        data = self.cleaned_data
        target = data["target_date"]
        project = data["project"]
        if target > project.target_date:
            raise forms.ValidationError("Target Date is beyond the project target date - Project Target: %s" % target)
        if target < project.start_date:
            raise forms.ValidationError("Target Date is before the start date of the project - Project Start: %s" % project.start_date)
        return data

MilestoneFormSet = modelformset_factory(Milestone, form=MilestoneForm, extra=1, max_num=50)

1 个答案:

答案 0 :(得分:1)

问题是Milestone.project可以是None

当您project = data['project']通过支票if project is None: raise forms.ValidationError('No project is assigned to this milestone.'

进行跟踪时

我之前提到过这个问题too,一定是错过了它。)。