Python Django - 显示 ImageField
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17846290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django - Display ImageField
提问by unixeO
i just start to use django and i haven't found a lot of info on how to display an imageField, so i made this:
我刚开始使用 django,我还没有找到很多关于如何显示 imageField 的信息,所以我做了这个:
models.py
模型.py
class Car(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=5, decimal_places=2)
photo = models.ImageField(upload_to='site_media')
views.py
视图.py
def image(request):
carx = Car()
variables = RequestContext(request,{
'carx':carx
})
return render_to_response('image.html',variables)
image.html
图像.html
{% extends "base.html" %}
{% block content %}
<img src=carx />
{% endblock %}
I already save an image since terminal and i know is there, also if a do this in image.html:
我已经从终端保存了一个图像,我知道在那里,如果在 image.html 中执行此操作:
{% block content %}
{{ carx }}
{% endblock %}
The ouput is: Car object
输出是: Car 对象
Can anyone tell me where is my error?
谁能告诉我我的错误在哪里?
Thanks a lot.
非常感谢。
采纳答案by voithos
An ImageField
contains a url
attribute, which you can use in your templates to render the proper HTML.
AnImageField
包含一个url
属性,您可以在模板中使用它来呈现正确的 HTML。
{% block content %}
<img src="{{ carx.photo.url }}">
{% endblock %}
回答by unixeO
Thanks to all, i fix it in this way.
感谢所有人,我以这种方式修复它。
views.py
视图.py
def image(request):
carx = Car.objects.all()
for mycar in carx:
MyCar = mycar.photo.url
variables = RequestContext(request,{
'carx':MyCar
})
return render_to_response('image.html',variables)
image.html
图像.html
{% extends "base.html" %}
{% block content %}
<img src="{{ MEDIA_URL }}{{ carx }}"/>
{% endblock %}
settings.py
设置.py
MEDIA_URL = '/Users/gcarranza/PycharmProjects/django_bookmarks/'
STATIC_URL = '/Users/gcarranza/PycharmProjects/django_bookmarks/site_media/'
STATICFILES_DIRS = (
'/Users/gcarranza/PycharmProjects/django_bookmarks/site_media',)
Now i know that carx.photo.url retrieve the absolute path of the file and its only matter to load as static file.
现在我知道 carx.photo.url 检索文件的绝对路径,它唯一的问题是作为静态文件加载。
回答by Vincent Verloop
You can also make use of the Static URL in Settings.py. Make a directory for example "Uploads", in the Static directory of your app. Also change this in your model in models.py
.
您还可以使用 Settings.py 中的静态 URL。在您的应用程序的静态目录中创建一个目录,例如“上传”。也在你的模型中改变这一点models.py
。
Use the following code:
使用以下代码:
<img src="{% static carx.photo.url %}" />