Django MEDIA_根和MEDIA_URL模板

2024-10-01 07:37:47 发布

您现在位置:Python中文网/ 问答频道 /正文

模型看起来像

class Cars(models.Model):
    name = models.CharFidle(max_length=255)
    price = models.DecimalField(max_digits=5,decimal_places=2)
    photo = models.ImageField(upload_to='images/cars')
    def __unicode__(self):
        return self.name

设置

^{pr2}$

但当我在这样的模板中使用它时

{% for car in cars %}
        <li>{{ car.name }}</li>
        <li>{{ car.price }}</li>
        <a>{{ car.photo }}</a>
        <img src="{{ car.photo.url }}"/>
    {% endfor %}

我拿不到图像,怎么了?在

如果有人帮我,那就太好了


Tags: name模型selfmodelmodelslicarcars
3条回答
urlpatterns = [
  # ... the rest of your URLconf goes here ..
  ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

将此添加到我的根目录网址.py记住在根中网址.py

从你的设置.py我假设您在基本目录中创建了一个介质文件夹。如果你有,那你就走对了。我想问题出在你的模板上。在

试试这个:

<img src="/static/{{car.photo}}" width="100" height="100" />

在扩展基之后,不要忘记在模板的顶部包含{% load staticfiles %}。。你准备好了。。。在

这里可能会发生一些事情:

  1. 您正在运行一个未设置为提供静态媒体的非开发web服务器。这里的解决方案将根据您运行的web服务器而有所不同。在
  2. 您正在运行开发web服务器,但尚未设置static serving。为此,我将在根目录中添加以下内容网址.py文件:
  urlpatterns = [
      # ... the rest of your URLconf goes here ...
  ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  1. 您的媒体根目录中存在权限问题。在本例中,我将确保您的媒体根目录可以被您的web服务器读取。在

相关问题 更多 >