gpt4 book ai didi

python - 在哪里/如何替换 Django CBV 中的默认上传处理程序?

转载 作者:太空宇宙 更新时间:2023-11-04 09:51:56 24 4
gpt4 key购买 nike

我正在尝试为基于类的 View 指定处理文件上传的特定方法。根据 docs这可以通过类似的方式实现:

from django.core.files.uploadhandler import TemporaryFileUploadHandler
request.upload_handlers = [TemporaryFileUploadHandler(request=request)]

如果我在 FormViewpost 方法中指定它,如下所示:

def post(self, request, *args, **kwargs):
request.upload_handlers = [TemporaryFileUploadHandler(request=request)]
return super().post(self, request, *args, **kwargs)

我得到:

AttributeError: You cannot set the upload handlers after the upload has been processed.

类似的变体产生相同的结果:

def post(self, request, *args, **kwargs):
self.request.upload_handlers = [TemporaryFileUploadHandler(request=self.request)]
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)

但是,当我在 get 方法中执行此操作时,这是无效的:

 def get(self, request, *args, **kwargs):
request.upload_handlers = [TemporaryFileUploadHandler(request=self.request)]
return super().get(self, request, *args, **kwargs)

如果我上传一个小文件,它仍然使用默认的 django.core.files.uploadhandler.MemoryFileUploadHandler

我做错了什么?

编辑

此外,当我尝试反射(reflect) note 中的建议时, 我得到相同的 AttributeError:

from django.views.decorators.csrf import csrf_exempt, csrf_protect

@csrf_exempt
def post(self, request, *args, **kwargs):
request.upload_handlers = [TemporaryFileUploadHandler(request=request)]
return self._post(request, *args, **kwargs)

@csrf_protect
def _post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)

最佳答案

好的,终于让它工作了(使用@Alasdair 提供的建议)。在 post 上设置一个 method decorator(crsf_exempt) 是不够的,它需要在 dispatch 上。对于将来为此苦苦挣扎的任何人,它是这样的:

from django.views.generic import FormView
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt, csrf_protect


@method_decorator(csrf_exempt, 'dispatch')
class UploadDataSetView(FormView):

def post(self, request, *args, **kwargs):
request.upload_handlers = [TemporaryFileUploadHandler(request=request)]
return self._post(request)

@method_decorator(csrf_protect)
def _post(self, request):
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)

如果您从模板中删除 {% csrf_token %}(这正是您想要的),它也会失败。

关于python - 在哪里/如何替换 Django CBV 中的默认上传处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47438330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com