[英]Django - Image from MEDIA_URL not showing up on template?
因此,我已經閱讀了許多有關此問題的堆棧溢出答案,但是似乎都無法解決我的問題。 我已經設置了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/'
型號
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>
因此,如您所見,如果我沒有上傳圖片用於發布,它將轉到默認圖片,該圖片存儲在static / textchange中。 該圖像將顯示在模板上。 如果我確實上傳圖片,則圖片不會顯示在模板上。 在我的template.html文件中,我在段落標記中添加了文本{{posts.image.url}},以查看不同圖像的url外觀。
使用static / textchange中的默認圖像時,URL為:/../static/textchange/nophoto.jpg,該圖像顯示良好。
當我嘗試在模板中顯示上載的圖像時,URL為:/media/postingpics/2015/09/20/Star-Wars-Sith-Code-Wallpaper-2_dlPszgQ.jpg並且沒有圖像出現...
我覺得靜態圖片在靜態圖片前面有/../很奇怪,但是我不知道為什么只顯示靜態文件夾中的圖片。
任何幫助,將不勝感激。
MEDIA_URL不是Django自動提供的,您必須手動設置。 https://docs.djangoproject.com/zh-CN/1.8/howto/static-files/#serving-files-uploaded-by-a-user-during-development
另外,您的靜態文件和媒體文件的設置也很奇怪:
看來您想要更多類似這樣的東西:
STATICFILES_DIRS = (
'/home/joe/Documents/exchange/Texchange/textchange/static',
)
MEDIA_ROOT = '/home/joe/Documents/exchange/Texchange/textchange/media/'
MEDIA_URL = '/media/'
STATIC_ROOT = '/home/joe/Documents/exchange/Texchange/textchange/static_root/'
STATIC_URL = '/static/'
假設Texchange/textchange
是您的項目根目錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.