1

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

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

它出错了

if target > project.target_date:

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

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

视图.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))

模型.py

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

表格.py

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

我希望使用验证的代码。现在除了forms.py之外一切都一样:

表格.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)
4

1 回答 1

1

问题是 Milestone.project 可以是None.

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

我也提到了你之前的问题,一定错过了:)。

于 2010-11-06T01:01:05.970 回答