簡體   English   中英

無法在Django模板中顯示ImageField

[英]Unable to display ImageField within Django template

希望您能為我的Django項目提供幫助。 我可以根據子彈的名稱在文件夾中的media_cdn文件夾下上傳圖像。 當我嘗試在我的帖子列表和帖子中顯示圖像時,會出現問題。

您能否看一下我的代碼並提供解決方案。 我花了幾個小時試圖使其工作。 請幫忙。

settings.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn/')

models.py

def upload_location(instance, filename):
    return "%s/%s" %(instance.slug, filename)

class Post(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250, unique=True)
    image = models.ImageField(upload_to=upload_location,
            null=True, 
            blank=True,
            width_field="width_field", 
            height_field="height_field")
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)
    body = models.TextField()
    date = models.DateTimeField()
    updated = models.DateTimeField(auto_now=True)

postlist.html

{% block content %}
    {% for post in posts %}
        <div class="container w3-card-4">
        {% if post.image %}
            <img src="{{ post.instance.image.url }}">
        {% endif %}
...

post.html

{% block content %}
<div class="row">
    <div class="container w3-card-4">
        {% if instance.image %}
        <img src= "{{ instance.image.url }}" class="img-responsive">
        {% endif %}
...

url.py

from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('personal.urls')),
    url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

我不知道還有什么嘗試從該文件夾中調用該圖像的。 任何建議將不勝感激。 謝謝!

使用post.image.url而不是post.instance.image.url 檢查文檔

ImageField繼承的所有屬性FileField包括url

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM