gpt4 book ai didi

Django表单上传request.files为空

转载 作者:行者123 更新时间:2023-12-04 20:20:22 25 4
gpt4 key购买 nike

我以前没有在这里发布过问题,主要阅读。

我正在学习 Django 并在 .但现在我以某种方式打破了它。

我上传时 request.FILES 为空,但我可以在 request.raw_post_data 中看到文件名。

这是 html 的代码

<form enctype="multipart/form-data" method="post" action="">{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value="Upload Photo" />
</form

表格

class PhotoUploadForm(forms.Form):
title = forms.CharField(max_length=50)
description = forms.CharField(required=False,max_length="254")
photo = forms.ImageField()


View
class PhotoUploadView(FormView):

template_name ="album/photo_upload.html"
form_class = PhotoUploadForm

def get_context_data(self,**kwargs):
context = super(PhotoUploadView,self).get_context_data(**kwargs)
context['user_info'] = self.request.user
if 'upload_form' in kwargs:
context['upload_form'] = kwargs['upload_form']
else:
context['upload_form'] = PhotoUploadForm()
album = get_object_or_404(Album,id=self.kwargs['album_id'])
context['album'] = album
context['form'] = self.form_class
return context

def post(self,*args,**kwargs):
print self.request.FILES
print self.request.raw_post_data
if self.request.method == "POST":
form = PhotoUploadForm(self.request.POST,self.request.FILES)
if form.is_valid():
photo = Photo()
photo.title = form.cleaned_data['title']
photo.summary = form.cleaned_data['description']
photo.album = get_object_or_404(Album,id = kwargs['album_id'])
photo.is_cover_photo = True
path = self.generate_filename(self.request.FILES['photo'].name,self.request.user,kwargs['album_id'])
destination = open(path,"wb+")
for chunk in self.request.FILES['photo'].chunks():
destination.write(chunk)
destination.close()
photo.imagePath = path
photo.save()
return self.render_to_response(self.get_context_data(upload_form=form)

最佳答案

我也使用 FormView 做到了(我主要是学习如何使用它,最新通用类 View 的 django doc 非常有限);虽然@bezidejni 的回答可能是一个更好的解决方案,但这就是您解决问题的方法:

class PhotoUploadView(FormView):

template_name ="album/photo_upload.html"
form_class = PhotoUploadForm

def form_valid(self, form):
"""
This is what's called when the form is valid.
"""
photo = form.cleaned_data['photo'] # <= this is your uploaded file in memory
# read your photo object by chunks, save it to disk, or whatever else
# ....
# then keep on going! you can make the 'get_success_url' more complex should you need to.
return HttpResponseRedirect(self.get_success_url())

附注。
如果您使用 FormView,则不应使用 render_to_response;过载 get_context_data如果您需要将上下文传递给已指定为 template_name 的模板

关于Django表单上传request.files为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7288528/

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