django:form_valid()缺少1个必需的位置参数:“ form”

时间:2018-11-22 10:54:24

标签: django django-templates django-views

我想知道如何在form_valid()函数中解决此问题:

  

form_valid()缺少1个必需的位置参数:“ form”

我正在使用Django Class Based Viewformsets。但是,可能会得到IntegrityError,我添加了try/except以便在表单有效时保存表单集,并在出现此问题时使用错误消息重定向模板。

class AnimalCreateView(CreateView):
    model = Animal
    template_name = 'animal_form.html'

    def get_context_data(self, **kwargs):
        context = super(AnimalCreateView, self).get_context_data(**kwargs)
        foo_queryset = Foo.objects.all()
        context['FooFormSets'] = FooFormSet(self.request.POST or None, self.request.FILES or None,
                                                      prefix='foo', queryset=foo_queryset)
        return context

    def form_valid(self, request, form):
        context = self.get_context_data()
        formsets = context['FooFormSets']
        if form.is_valid():
            self.object = form.save()
            try:
                if formsets.is_valid():
                    formsets.instance = self.object
                    formsets.save(commit=False)
                    for element in formsets:
                        element.save(commit=False)
                        formsets.save()
            except IntegrityError:
                messages.error(self.request, _(f"Issue with foo"))
                return render(request, self.template_name)

        return super(AnimalCreateView, self).form_valid(form)

我想知道我在form_valid()函数中必须执行的操作,以解决我的问题并使用错误消息将用户重定向到同一模板格式。

谢谢

1 个答案:

答案 0 :(得分:4)

def form_valid(self, request, form):应该是def form_valid(self, form):

您可以通过self.request访问请求对象。

def form_valid(self, form):
    context = self.get_context_data()
    formsets = context['FooFormSets']
    if form.is_valid():
        self.object = form.save()
        try:
            if formsets.is_valid():
                formsets.instance = self.object
                formsets.save(commit=False)
                for element in formsets:
                    element.save(commit=False)
                    formsets.save()
        except IntegrityError:
            messages.error(self.request, _(f"Issue with foo"))
            return render(self.request, self.template_name)

此外,您不必再次调用if form.is_valid():,因为已经确定-因此可以执行form_valid