将文件上传到django PYTHON中的自定义目录

时间:2013-08-14 06:42:05

标签: python django file-upload error-handling

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

观点功能

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.

2 个答案:

答案 0 :(得分:1)

错误表明您的视图未返回任何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 })

答案 1 :(得分:0)

关于该错误,问题出现在您的视图中:如果您的表单无效,则表示您没有向客户返回响应:

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

# *** Unindented
return render_to_response('user_profile.html', { 'form': form })

另外(我没有多少文件上传经验),但我认为您不需要进行is_multipart检查 - 这可能会导致您的表单无效。