所以我已經閱讀了關於這個問題的一些堆棧溢出的答案,但沒有一個能夠解決我的問題。我設置了MEDIA_ROOT,MEDIA_URL,STATIC_ROOT和STATIC_URL,但由於某些原因,我的media_url中的圖像沒有顯示在我的模板上,而來自我的static_url的圖像是。Django - 來自MEDIA_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/'
Models.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'
Template.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>
所以你可以看到,如果我沒有上傳圖片的帖子它會轉到默認圖像,該圖像存儲在靜態/文本更改中。該圖像將顯示在模板上。如果我上傳圖片,圖片將不會顯示在模板上。在我的template.html中,我在段落標籤中顯示了{{posting.image.url}}文字,以查看不同圖片的網址。
當使用static/textchange中的默認圖像時,url爲:/../static/textchange/nophoto.jpg,圖像顯示正常。
當我嘗試在模板中顯示上傳的圖像時,網址爲:/media/postingpics/2015/09/20/Star-Wars-Sith-Code-Wallpaper-2_dlPszgQ.jpg並且沒有圖像出現。 ..
我覺得很奇怪,靜態圖像在靜態前面有/../,但我不知道爲什麼只顯示靜態文件夾中的圖像。
任何幫助,將不勝感激。
嗯,我有一個媒體文件夾和我的應用程序文件夾內的靜態文件夾。但如果我把靜態結束STATIC_ROOT我的CSS文件停止加載... – Programmingjoe
我服務的媒體文件就像你說的,它的工作原理:) – Programmingjoe
STATIC_ROOT是不是真正用於開發,該文件夾只是存在(如果我記得正確)。只要'static'文件夾在STATICFILES_DIRS中就像上面一樣,它將被提供 – mindcruzer