基于Django类的视图:发布表单数据返回302 Found状态代码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于Django类的视图:发布表单数据返回302 Found状态代码相关的知识,希望对你有一定的参考价值。

我正在使用django基于通用类的视图CreateView将图像上传到书中。这是代码:

# models.py
class Upload(models.Model):
    image = models.ImageField(upload_to=get_upload_path, help_text='Image to process')
    uploader = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name='uploader')
    language = models.ForeignKey(Language, models.CASCADE)
    book = models.ForeignKey(Book, models.CASCADE)

    def __str__(self):
        return str(os.path.split(self.image.name)[-1].split('_', 1)[-1])

    @models.permalink
    def get_absolute_url(self):
        return ('book:upload_new', (self.book.id,))     # upload_new is linked to the view below

    def save(self, *args, **kwargs):
        super(Upload, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        self.image.delete(False)
        super(Upload, self).delete(*args, **kwargs)


# views.py
@method_decorator(login_required, name='dispatch')
class PictureCreateView(CreateView):
    model = Upload
    fields = ("image",)
    book_id = None

    def dispatch(self, *args, **kwargs):
        # book_id is passed as a URL parameter
        self.book_id = self.kwargs['book_id']
        return super().dispatch(*args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(PictureCreateView, self).get_context_data(**kwargs)
        context['book_id'] = self.book_id
        return context

    def form_valid(self, form, **kwargs):
        book = Book.objects.get(id=self.book_id)
        form.instance.book = book
        form.instance.language = book.language
        form.instance.uploader = self.request.user
        self.object = form.save()

        # Running the command below prints
        # <TemplateResponse status_code=200, "text/html; charset=utf-8">
        # implying the upload was successful
        #
        # print(self.render_to_response(context=self.get_context_data()))

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

    def form_invalid(self, form):
        print(form.errors)
        data = json.dumps(form.errors)
        return HttpResponse(content=data, status=400, content_type='application/json')

当我尝试上传图片时,我收到此请求的302 Found错误(如我浏览器的开发工具中所示),暗示页面已暂时移动。除了标题之外,我无法看到此请求的预览或响应。上传成功虽然(我在管理页面中查看过)。

之前有人有this issue,答案指出了URL conf中的错误。但是,该问题尚未完全解决,OP仍然获得302状态代码。

这可能是什么原因?

答案

默认情况下,form_valid方法将302代码重定向到success_url(可以通过覆盖get_success_url动态生成)。所以这是正常的行为,我认为这是一种很好的做法。所以我不会改变它。

但是如果你真的想要,你可以返回任何其他响应代码,例如:一个内容与get相似的200代码

# views.py
@method_decorator(login_required, name='dispatch')
class PictureCreateView(CreateView):
    ...

    def form_valid(self, form, **kwargs):
        book = Book.objects.get(id=self.book_id)
        form.instance.book = book
        form.instance.language = book.language
        form.instance.uploader = self.request.user
        self.object = form.save()

        context = self.get_context_data()
        # You may have check and modify your context for a correct page
        # May be: add new things
        context["success"] = True

        return self.render_to_response(context))

以上是关于基于Django类的视图:发布表单数据返回302 Found状态代码的主要内容,如果未能解决你的问题,请参考以下文章

基于 Django 类的视图加载另一个带有数据的表单

将 html 表单数据获取到基于 django 类的视图中

Django 在基于类的视图中处理多个表单

Django:基于类的视图无法呈现清晰的表单

Django 基于类的视图:覆盖表单名称

Django 基于类的视图是不是自动为模板分配表单值