gpt4 book ai didi

python - 将文件上传到Django PYTHON中的自定义目录

转载 作者:行者123 更新时间:2023-12-03 08:32:59 24 4
gpt4 key购买 nike

我有自定义表单,需要将其上传到某个目录,下面是代码

View 功能

def user_profile(request):
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid() and form.is_multipart():
new_user = save_file(request.FILES['image'])
return HttpResponse(new_user)
else:
form = ImageForm()
return render_to_response('user_profile.html', { 'form': form })



def save_file(file, path='home/ghrix/ghrixbidding/static/images/'):
''' Little helper to save a file
'''
filename = file._get_name()
fd = open('%s/%s' % (MEDIA_ROOT, str(path) + str(filename)), 'wb')
for chunk in file.chunks():
fd.write(chunk)
fd.close()

下面是表格:
<form method="POST" class="form-horizontal" id="updateform" name="updateform" enctype="multipart/form-data" action="/user_profile/">{% csrf_token %}
<input type="file" id="fileinput" name="fileinput" />
<button class="btn btn-gebo" type="submit">Save changes</button>
</form>

但出现此错误:
The view userprofile.views.user_profile didn't return an HttpResponse object.

最佳答案

该错误表明您的 View 未返回任何HttpResponse。有一种情况是可能的-

def user_profile(request):
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid() and form.is_multipart():
new_user = save_file(request.FILES['image'])
return HttpResponse(new_user)
# ------^
# There is not else check. It's possible that the if condition is False.
# In that case your view is returning nothing.
else:
form = ImageForm()
return render_to_response('user_profile.html', { 'form': form })

关于python - 将文件上传到Django PYTHON中的自定义目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18224873/

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