ImageField Django模板 [英] ImageField Django template

查看:127
本文介绍了ImageField Django模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Django的新手。我在文档和此站点上阅读了很多有关我的问题的内容。但是我真的不明白该怎么做。有人可以告诉我所有步骤吗?

I'm new in Django. I read a lot on documentation and on this site about my question. But I really can not understand what I should do to make this. Can someone show me with all steps please?

model.py:

class Post(models.Model):
    title=models.CharField(max_lengt=50)
    img=models.ImageField(upload_to = 'images')

模板:

{% for post in posts %}
     <h1> {{post.title}} </h1>
     <img src="{{post.img}}">
{% endfor %} 

settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

如果我访问管理页面,如何上传图像?在模板中看不到图片!

If I access the admin page, how can I upload the image? In template I can't see image!

对不起,我的英语不好。

Sorry for my bad English. Help me please

推荐答案

模板中,使用:

{% for post in posts %}
<h1> {{post.title}} </h1>
<img src="{{ post.img.url }}"> 
{% endfor %}

您必须添加 {{ post.img.url}}

另外,请确保在 urls.py ,您有:

Also, make sure that in urls.py, you have:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

它将起作用。

这篇关于ImageField Django模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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