图像不会在 Django 中呈现

Image does not get rendered in Django

我摆弄了一下 django ImageField,
例如,我得到了以下模型

class Card(models.Model):
    name        =   models.TextField()
    mana        =   models.IntegerField()
    rarity      =   models.IntegerField(choices=RARITY_CHOICES)
    card_class  =   models.IntegerField(choices=CLASS_CHOICES)
    card_set    =   models.IntegerField(choices=SET_CHOICES)
    card_type   =   models.IntegerField(choices=TYPE_CHOICES)

    def __unicode__(self):
        return self.name

class Weapon(Card):
    damage      =   models.already created a deck with some cards in the django admin interface. Now finally I wanted to render it with a custom view in my template with this viewIntegerField()
    durability  =   models.IntegerField()
    image       =   models.ImageField(upload_to='/home/ubuntu/illuminated/media/images/weapons/')

class Deck(models.Model):
    name            =   models.CharField(max_length=20)
    spell_cards     =   models.ManyToManyField(Spell, blank=True)
    weapon_cards    =   models.ManyToManyField(Weapon, blank=True)
    minion_cards    =   models.ManyToManyField(Minion, blank=True)

我已经在 django 管理界面中创建了一个带有一些卡片的卡片组。现在终于我想用我的模板中的自定义视图用这个视图渲染它

class ShowDeck(TemplateView):
    template_name = 'hsguides/deck.html'

    def get_context_data(self, **kwargs):
        context = super(ShowDeck, self).get_context_data(**kwargs)
        context['deck'] = Deck.objects.all()
        return context

还有这个简单的模板 已经在 django 管理界面中创建了一个带有一些卡片的卡片组。现在终于我想用我的模板中的自定义视图用这个视图渲染它

{% for foo in deck.all %}
  {{ foo.name }}
  <br>
  {% for weapon in foo.weapon_cards.all %}
    {{ weapon.name }}
    <img src="{{ weapon.image }}" height="{{ weapon.image.height }}" width="{{ weapon.image.width }}">
  {% endfor %}
{% endfor %}

名称正在呈现,当我查看页面源代码时,图像 url、宽度和高度也是如此,但图像根本不显示。
当我在浏览器中单击 查看图像 时,我看到以下错误

Using the URLconf defined in illuminated.urls, Django tried these URL patterns, in this order:

^admin/
^account/
^guides/

The current URL, home/ubuntu/illuminated/media/images/weapons/Truesilver_Champion_Gold_ktmWGK8.png, didn't match any of these

目前看起来像这样

页面源代码如下所示

  Basic Paladin
  <br>

    Truesilver Champion
    <img src="/home/ubuntu/illuminated/media/images/weapons/Truesilver_Champion_Gold_ktmWGK8.png" height="396" width="289">

非常感谢任何形式的帮助!

简而言之:


将 upload_to 属性设置为 images/weapons/ 并添加

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

到你的根 urls.py。

还要确保在您的设置中定义了 MEDIA_ROOTMEDIA_URL:

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

解释:


在您的 models.py 中,您将 class WeaponImageField 的 upload_to 属性设置为本地文件系统上的绝对路径:/home/ubuntu/illuminated/media/images/weapons

然而,在您的浏览器上下文中,任何以 / 开头的路径都被解释为相对于主机的绝对路径。如果您的主机名是 localhost 并且您的服务器是端口 8000 上的 运行 它将查找该文件 http://localhost:8000/home/ubuntu/......./weapons/file.jpg.

当 django 处理请求时,它会尝试匹配以 home 开头的请求路径,但是由于您没有配置路由来解析 home,因此您会收到此错误。