ProductCreateView 视图没有 return HttpResponse 对象。它 return 改为 None

The view ProductCreateView didn't return an HttpResponse object. It returned None instead

如何在通用 FormView.

中从 def form_valid(self): 重定向到另一个页面

我知道我应该做类似 Super(className, self).form_valid(form): 的事情,但这永远不会重定向到动态 link,而只会转到 success URL

这是我的代码:

class ProductCreateView(FormView):
    form_class = ProductCreateForm
    template_name = 'back_office/product_create_form.html'
    success_url = reverse_lazy('product_recipe_wrapper')

    def form_valid(self, form):
        category = Category.objects.get(id=self.kwargs['pk'])
        name = form.cleaned_data['name']
        image = form.cleaned_data['image']
        big_size = form.cleaned_data['big_size']
        mid_size = form.cleaned_data['mid_size']
        small_size = form.cleaned_data['small_size']
        new_product = Product.objects.create(category=category, name=name, image=image)
        big_size_object = ProductSize.objects.create(product=new_product, size=Size.objects.get(id=1),
                                                     sell_price=big_size)
        mid_size_object = ProductSize.objects.create(product=new_product, size=Size.objects.get(id=2),
                                                     sell_price=mid_size)
        small_size_object = ProductSize.objects.create(product=new_product, size=Size.objects.get(id=3),
                                                       sell_price=small_size)
        if small_size_object.sell_price != 0:
            return reverse_lazy('product_small_recipe', args=[small_size_object.id])

    def get_context_data(self, *args, **kwargs):
        context = super(ProductCreateView, self).get_context_data()
        context['category'] = Category.objects.get(id=self.kwargs['pk'])
        return context

form_valid 方法需要 return 响应。错误消息 It returned None instead 意味着该方法根本没有 return 任何东西。在上面的代码中,当 small_size_object.sell_price == 0:.

时会发生这种情况

接下来,您不能执行 return reverse_lazy(...),因为该方法需要 return 一个 响应 ,而不是 URL。如果要重定向,可以使用HttpResponseRedirect,例如:

from django.http import HttpResponseRedirect

class ProductCreateView(FormView):
    ...

    def form_valid(self, form):
        ...
        return HttpResponseRedirect(reverse('product_small_recipe', args=[small_size_object.id]))

请注意,您可以在此处使用 reverse 而不是 reverse_lazy,因为您在方法中。

您可以使用 redirect 快捷方式简化代码。

from django.shortcuts import redirect

class ProductCreateView(FormView):
    ...

    def form_valid(self, form):
        ...
        return redirect('product_small_recipe', small_size_object.id)