Django,ImageFiled上传照片并显示

来源:互联网 发布:实战nginx 下载 编辑:程序博客网 时间:2024/04/30 02:16

1:首先理解settings.py中

MEDIA_ROOT:
MEDIA_URL:这两者之间的关系。
MEDIA_ROOT:就是保存上传图片的根目录,比如说MEIDA_ROOT ="C:\\Django\\Photo",则上传的照片就在这个文件夹中,如果ImageFiled中设置了upload_to,这个upload_to则让图片是上述根目录中子目录中存储。upload_to注意设置要区分有没有 " / " ,例如 upload_to='photo' 与 upload_to = " /phto/ ”就会造成完全不同的后果,前面的用法是正确的。

MEDIA_URL:主要用于URL映射这块,与urls.py中一个映射有关系

例如:MEDIA_URL = '/media/', 这个MEDIA_URL是添加在ImageFIeld中存储路径的公共目录.例如 

img=models.ImageField(upload_to='photo',null=False,blank=True)

则这个img的url属性就是 “/media/photo/xxx.jpg ,然后就需要考虑在Url文件中的映射,要在模板中访问该图片文件,则 img的src 设置为 {{ example.img.url }}即可

urls.py中应该添加如下一条映射  (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),

其中url中media就对应着MEDIA_URL中的配置,对 这类网址的访问都映射到MEDIA_ROOT这个目录,并根据ImageFIled中存储的相对路径进行访问。

把上述这几个之间关系弄明白,使用ImageField上传图片并显示就很容易

参考下列例子

#models.pyclass Img(models.Model):name=models.CharField(max_length=30)img=models.ImageField(upload_to='photo',null=False,blank=True)def __unicode__(self):return self.name

#forms.pyclass ImgForm(ModelForm):class Meta:model=Img

#views.py@csrf_exempt def add(request):if request.method == 'POST':form = ImgForm(request.POST,request.FILES)if form.is_valid():form.save()else:form = ImgForm()return render_to_response('add.html', {'form': form})def list(request):    template_var={}    photos=Img.objects.all()    template_var['pics']=photos    return render_to_response('list.html',template_var,                       context_instance=RequestContext(request))

#settings.pyMEDIA_ROOT = "/xxxxx/media/"# URL that handles the media served from MEDIA_ROOT. Make sure to use a# trailing slash if there is a path component (optional in other cases).# Examples: "http://media.lawrence.com", "http://example.com/media/"MEDIA_URL = '/media/'

#urls.py(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),


#模板<body>{% for photo in pics %}<h3><p class="greentitle"> {{photo.name}} </p></h3><a href="{{photo.img.url}}"><img  src="{{photo.img.url}}" alt="{{photo.img.url}}"></img></a>{% endfor %}</body>
#模板<body>    <form enctype="multipart/form-data" action="" method="post">        {{ form.as_p }}        <input type="submit" value="Submit" />    </form></body>



0 0
原创粉丝点击