Django 根据同时处理的另一个表单验证表单集中的字段

发布于 2024-09-30 12:29:44 字数 2338 浏览 4 评论 0原文

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

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

它在异常值上出错

if target > project.target_date:

:“NoneType”对象没有属性“target_date”

当前无需验证即可使用的代码:注意,我将项目设置为允许里程碑模型上为空。我希望它不允许为 null,但这是我能够弄清楚如何将 project_id 传递到 Milestones 表单的唯一方法。

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)

This one might be a bit complicated or I am just confused

I have two forms on a single page. One is a form and the other is a formset. My goal is to validate fields in the formset against fields in the form. My guess on what is currently happening is that the method that I am passing the Project forms ID to the formset is happening in a way that it's not being picked up for the formsets validation.

It errors out on

if target > project.target_date:

Exception Value: 'NoneType' object has no attribute 'target_date'

The code that currently works with out validation: Note, I am setting project to allow null on the Milestones model. I would prefer it to not allow null but this was the only way I could figure out how to pass the project_id to the Milestones form.

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)

The code that I would like have work with validation. Right now everything is the same except 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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

微凉徒眸意 2024-10-07 12:29:44

问题是 Milestone.project 可能是 None

当您执行project = data['project']时,请检查如果项目为None:raise forms.ValidationError('没有项目分配给此里程碑。'

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

The issue is that Milestone.project can be None.

When you do project = data['project'] follow it on by a check if project is None: raise forms.ValidationError('No project is assigned to this milestone.'

I mentioned this your previous question too, must have missed it :).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文