【发布时间】:2015-12-17 00:18:59
【问题描述】:
所以我已经阅读了一些关于这个问题的堆栈溢出答案,但似乎没有一个可以解决我的问题。我已经设置了 MEDIA_ROOT、MEDIA_URL、STATIC_ROOT 和 STATIC_URL,但由于某种原因,我的 media_url 中的图像没有显示在我的模板上,而我的 static_url 中的图像是。
下面是我的代码以及进一步的解释。
Settings.py
STATICFILES_DIRS = (
('/static/',
'/home/joe/Documents/exchange/Texchange/textchange/static',),
('/media/',
'/home/joe/Documents/exchange/Texchange/textchange/media/',),
)
MEDIA_ROOT = '/home/joe/Documents/exchange/Texchange/textchange/media/'
MEDIA_URL = '/media/'
STATIC_ROOT = '/home/joe/Documents/exchange/Texchange/textchange/'
STATIC_URL = '/static/'
模型.py
class Posting(models.Model):
textbook = models.ForeignKey(Textbook)
condition = models.CharField(max_length = 200)
price = models.DecimalField(max_digits=5, decimal_places=2)
user = models.ForeignKey(User)
image = models.ImageField(upload_to='postingpics/%Y/%m/%d', default="../../static/textchange/nophoto.jpg")
post_date = models.DateTimeField('date_posted')
def __str__(self):
return str(self.textbook)
def was_posted_recently(self):
return self.post_date >= timezone.now() - datetime.timedelta(days=1)
was_posted_recently.admin_order_field = 'post_date'
was_posted_recently.boolean = True
was_posted_recently.short_description = 'Posted recently'
模板.html
<div class="row marketing">
<div class="col-lg-6">
<h3>Textbook Info</h3>
<p><strong>Textbook: </strong>{{ posting.textbook.textbook_name }}</p>
<p><strong>Condition: </strong>{{ posting.condition }}</p>
<p><strong>Price: </strong>{{ posting.price }}</p>
<p><strong>Class: </strong>{{ posting.textbook.class_name }}</p>
<p><strong>ISBN: </strong>{{ posting.textbook.isbn }}</p>
<p><strong>Author: </strong>{{ posting.textbook.author }}</p>
<h3>Contact Info</h3>
<p><strong>User: </strong>{{ posting.user.username }}</p>
<p>Button to contact</p>
</div>
<div class="col-lg-6">
{% block content %}
<img src="{{ posting.image.url }}">
<p>{{ posting.image.url }}</p>
{% endblock %}
</div>
</div>
如您所见,如果我不上传图片以进行发布,它会转到存储在静态/textchange 中的默认图片。此图像将显示在模板上。如果我确实上传了图像,该图像将不会显示在模板上。在我的 template.html 中,我在段落标签中有文本 {{ posting.image.url }} 以查看不同图像的 url 是什么样的。
当使用 static/textchange 中的默认图片时,url 为:/../static/textchange/nophoto.jpg 并且图片显示正常。
当我尝试在模板中显示上传的图片时,网址为:/media/postingpics/2015/09/20/Star-Wars-Sith-Code-Wallpaper-2_dlPszgQ.jpg 并且没有显示图片。 .
我发现静态图像如何在 static 前面有 /../ 很奇怪,但我不知道为什么只显示静态文件夹中的图像。
任何帮助将不胜感激。
【问题讨论】:
标签: python django django-templates media django-settings