简体   繁体   English

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

[英]upload file to custom directory in django PYTHON

i have custom form for which i need to upload the image to some directory , below is the code 我有自定义表单,需要将其上传到某个目录,下面是代码

views function 视图功能

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()

and below is the form: 下面是表格:

<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>

but am getting this error : 但出现此错误:

The view userprofile.views.user_profile didn't return an HttpResponse object.

The error says that your view is not returning any HttpResponse . 该错误表明您的视图未返回任何HttpResponse There is one case that it's possible - 有一种情况是可能的-

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 })

Regarding that error, the problem is in your view: if your form is invalid, you are not returning a response to the client: 关于该错误,您认为是问题所在:如果您的表单无效,则不会向客户返回响应:

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 })

also (I don't have much experience with file uploads) but I don't think you need the is_multipart check - it may be causing your form to appear invalid. 也(我对文件上传没有太多经验),但我认为您不需要进行is_multipart检查-这可能导致您的表单显得无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM