显示位于Django数据库中的图像 [英] Display an image located in the database in Django

查看:200
本文介绍了显示位于Django数据库中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想显示我通过admin模块通过网页上的html图像标签上传的图像。
图片位于/home/user/work/djcode/media/chicks/blondie.jpg。

I just want to display an image that i have uploaded through the admin module, through an html image tag on a web page. The image is located in /home/user/work/djcode/media/chicks/blondie.jpg.

以下是我模型中的相关部分。 py

Here is the relevant part of my models.py

class Image(models.Model):
    model_name = models.CharField(max_length=50)
    model_pic = models.ImageField(upload_to='chicks/')
def __unicode__(self):
    return self.model_name

这是我的观点的相关部分。py

Here is is the relevant part of my views.py

def main(request):
    i = get_object_or_404(Image, pk=1)
    return render_to_response('polls/main.html', {'image': i}, context_instance=RequestContext(request))

我使用的html标签只是

The html tag that i am using is simply

<img src="{{ MEDIA_ROOT }}/{{ image.model_pic.url }}">

从settings.py中,我的媒体根目录是MEDIA_ROOT ='/ home / user / work / dj / media'

From settings.py, my media root is MEDIA_ROOT = '/home/user/work/djcode/media'

请注意,变量{{image.model_pic.url}}通过html模板显示为 chicks / blondie.jpg,因此我认为我的图像对象是

Note that the variable {{ image.model_pic.url }} shows "chicks/blondie.jpg" through the html template so I think that my image object is indeed well sent to the template.

有人能帮我这个忙吗?那真的很有帮助。

Anyone could give me a hand with that ? That would be really helpful.

非常感谢您的时间!

推荐答案

您的使用模板中图片字段上的url函数不太正确- {{image.model_pic.url}} 应该可以解决此问题。您只需要删除 {{MEDIA_URL}} 位。

Your use of the url function on the image field in your template is not quite correct - {{ image.model_pic.url }} should fix the issue. You just need to drop the {{ MEDIA_URL }} bit.

您的html应该是-

<img src="{{ image.model_pic.url }}">

请查看在模型中使用文件

如果您仍然遇到问题,那么服务静态文件可能会出问题。 在django中提供静态文件的方式会有所不同,具体取决于您是在生产环境中进行操作还是仅使用 python manage.py runserver 命令。

If you're still having trouble then it may be an issue with serving static files. Serving static files in django varies depending on whether you're doing it in production or just using the python manage.py runserver command.

要在开发期间服务器媒体文件(使用python manage.py runserver),请确保您的settings.py中的MEDIA_URL和MEDIA_ROOT正确无误,然后可以将以下内容附加到url conf中-

To server media files during development (with python manage.py runserver), make sure you've got your MEDIA_URL and MEDIA_ROOT correct in your settings.py then you can append the following to your url conf -

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

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

看看 docs 有关如何在生产环境中提供文件的说明。

Have a look at the docs for instructions on how to serve files in production.

这篇关于显示位于Django数据库中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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