在Django中显示图像 [英] Display images in Django

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

问题描述

我有一个django应用程序,该应用程序允许用户使用它提交图像.现在,我的模型看起来像

I have a django app which allows users to submit an image with it. Right now my model looks like

class Posting(models.Model):
    title = models.CharField(max_length=150)
    images = models.ForeignKey(Image, null=True)

class Image(models.Model):
    img = models.ImageField(upload_to="photos/",null=True, blank=True)

,并且我试图在模板中显示图像,但是似乎无法正常工作.我走了无数堆栈溢出的帖子,也没有任何运气.在我的模板中,我有

and I am trying to display the images in my template however I cannot seem to get it to work. I have gone though countless stack overflow posts and haven't had any luck. In my template I have

{ for post in postings }
    <img src"{{ post.image.url }} #and many variations of this

但是其他似乎显示了该url.网址似乎总是空白.任何帮助将不胜感激!

however other seems to display the url. The url seems to always be blank. Any help would be greatly appreciated!

推荐答案

这就是我的工作方式.

settings.py

import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

MEDIA_ROOT = (
BASE_DIR
)


MEDIA_URL = '/media/'

models.py ...

image = models.ImageField(upload_to='img')

urls.py (项目的)

if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

模板(.html)

<img src="{{ post.image.url }}" alt="img">

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

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