如何处理“嵌套”表单中的错误

时间:2015-11-13 15:22:35

标签: django django-forms django-errors

我有两种模式:

class Building(models.Model):
    label = models.CharField(_("Building label"), blank=False, max_length=255)  

    def get_absolute_url(self):
        return reverse('buildings:config', kwargs={'pk': self.id})


class Floor(models.Model):

    label = models.CharField(_("Floor label"), blank=True, max_length=255)

    building = models.ForeignKey(Building, null=False)

我编写了一个自定义ModelForm,以便允许用户更改(UpdateView)建筑物的信息并在同一页面中添加新楼层(FloorsConfigForm)。

FloorsConfigForm是:

class FloorsConfigForm(forms.ModelForm):
    class Meta:
        model = Floor
        fields = ["label", "building",]

观点是:

class BuildingConfigUpdateView(LoginRequiredMixin, UpdateView):
    model = Building
    fields = ('label','address',)
    template_name = "buildings/building_update.html"
    form_floors = FloorsConfigForm(prefix="floor_")

    def get_context_data(self, **kwargs):
        ret = super(BuildingConfigUpdateView, self).get_context_data(**kwargs)
        ret["form_floors"] = self.form_floors
        b = Building.objects.get(id=self.kwargs["pk"])
        ret["floors"] = Floor.objects.filter(building=b)
        return ret

    def post(self, request, *args, **kwargs):
            res = None
            print(request.POST)
            if "action_save" in request.POST:
                res = super(BuildingConfigUpdateView, self).post(request, *args, **kwargs)
            elif "action_add_floor" in request.POST:
                # #add the floor , validate, save...
                self.form_floors = FloorsConfigForm(request.POST, prefix="floor_")
                if self.form_floors.is_valid():
                    self.form_floors.save()
                    res = HttpResponseRedirect(reverse('buildings:config', kwargs={"pk":self.kwargs["pk"]}))
                else:
                    print(self.form_floors.errors)
                    res = HttpResponseRedirect(reverse('buildings:config', kwargs={"pk":self.kwargs["pk"]}))

            else:
                res = HttpResponseRedirect(reverse('buildings:config', kwargs={"pk":self.kwargs["pk"]}))
            return res

这很有效,我很高兴(!)

但最后一英里是在其“父”的模板中正确显示我的form_floors表单的错误。

这就是我需要你的地方!

注意:在上面的视图代码中,我只是打印表单错误(print(self.form_floors.errors),这是正常的,因为它打印

"<QueryDict: {'csrfmiddlewaretoken': ['gcBxn72bm6cLFXmpIatplZ0cNtsNgMlU'], 'floor_-building': [''], 'action_add_floor': [''], 'floor_-label': ['']}>
<ul class="errorlist"><li>building<ul class="errorlist"><li>This field is required.</li></ul></li></ul>" 

当我没有指定建筑物到地板时。

确切的问题是:如何在主模板中呈现此错误消息?

编辑 - 越来越近了 在我的帖子def中,我改变了重定向:

def post(self, request, *args, **kwargs):
                res = None
                print(request.POST)
                if "action_save" in request.POST:
                    res = super(BuildingConfigUpdateView, self).post(request, *args, **kwargs)
                elif "action_add_floor" in request.POST:
                    # #add the floor , validate, save...
                    self.form_floors = FloorsConfigForm(request.POST, prefix="floor_")
                    if self.form_floors.is_valid():
                        self.form_floors.save()
                        res = HttpResponseRedirect(reverse('buildings:config', kwargs={"pk":self.kwargs["pk"]}))
                    else:
                        print(self.form_floors.errors)
                        res = super(BuildingConfigUpdateView, self).post(request, *args, **kwargs)

                else:
                    res = HttpResponseRedirect(reverse('buildings:config', kwargs={"pk":self.kwargs["pk"]}))
                return res

最好,我可以访问模板中的错误。但我的主要形式是空的!

这是真的,因为在我的模板中,我有两个html表单。因此,当我发送第二个表单时,POST请求没有其他kwargs。

现在,我需要找到一种方法来“融合”两个请求!

0 个答案:

没有答案