Django:图像上传到服务器 [英] Django: Image Upload to the Server

查看:130
本文介绍了Django:图像上传到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将图像上传到服务器。因为我已经创建了一个表单,在我的views.py文件中,我试图将它提交到服务器。在这里它不会将文件上传到images文件夹。而不是仅更新使用新映像名称提交的数据库。所以有人可以给我一个解决方案。

I want to upload the image to the server. for that I have created a form and within my views.py file I tried to submit it into the sever. Here it does not uploads the file to "images" folder. instead of that it only update the database filed with new image name. So can anyone give me a solution.

这是views.py文件

this is views.py file

@login_required
def edit_profile(request):

if request.POST:


        employee = Employee.objects.get(user=request.user)          
        employee.avatar=request.POST.get('image')
        employee.save()
        return HttpResponseRedirect('/view_profile/')       

user_profile = request.user.get_profile()
return render_to_response('edit_profile.html',{'profile':user_profile },context_instance=RequestContext(request))

这里是我的html代码

here my html code

   {% block content %}

<form action="." method="post">
{% csrf_token %}    

    <input type="file" name="image"/>
    <input type="submit" value="Save Changes" name="save" />        

</form>

{% endblock %}

图像文件夹

推荐答案

您需要添加 enctype =multipart / form-data / code>,您的表单元素,以便文件也上传到 request.FILES 中视图..

You need to add enctype="multipart/form-data" in your form element, so that files are also uploaded and available in request.FILES in the view..

所以更新到

<form action="." method="post" enctype="multipart/form-data" >

 ....

将上传的文件绑定到表单

要保存图像更容易使用 ModelForm 并适当地设置图像文件。但是你仍然要直接保存对象

To save the image its easier to use ModelForm and set image file appropriately. But still you want to save the object directly do

...
employee.avatar = request.FILES['image']
employee.save()

Ref 文件上传

这篇关于Django:图像上传到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆