我在基于Django中的ImageField提供图像时遇到问题。
models.py
部分看起来像这样:
class Post(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
category = models.ManyToManyField(Category)
trip = models.ForeignKey(Trip, on_delete=models.CASCADE)
main_image = models.ForeignKey(Image, on_delete=models.CASCADE, related_name='main_image')
images = models.ManyToManyField(Image, related_name='images')
class Image(models.Model):
name = models.CharField(max_length=32)
picture = models.ImageField(upload_to='pictures/', blank=True)
trip = models.ForeignKey(Trip, on_delete=models.CASCADE)
taken = models.DateTimeField(blank=True, null=True)
uploaded = models.DateTimeField(default=timezone.now)
def __unicode__(self):
return self.name
settings.py
包含MEDIA_URL和MEDIA_ROOT:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
还包括了我在urls.py
的其他SO主题中找到的内容:
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.contrib.staticfiles.urls import static, staticfiles_urlpatterns
from django.conf import settings
from markdownx import urls as markdownx
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
url(r'^markdownx/', include('markdownx.urls')),
] + staticfiles_urlpatterns() + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
最后,我将其放在html模板中,如下所示:
{% extends 'blog/base.html' %}
{% block leftcolumn %}
{% for post in posts %}
<div class="leftcolumn">
<div class="card" style="max-width: 100%">
<h2><a href="">{{ post.title }}</a></h2>
<h5>published: {{ post.published_date }}, by: {{ post.author }}</h5>
<div><img src="{{ post.main_image.url }}"></div>
<p>{{ post.byline }}</p>
</div>
</div>
{% endfor %}
{% endblock %}
但是未显示图像。
如果我转到网址host:8000/media/pictures/test_photo.jpg
,就可以看到该图片,通常我可以在页面上显示图片(例如,在django-markdownx字段中),但不能通过ImageField网址显示图片。
有什么想法吗?
答案 0 :(得分:3)
此行:
<div><img src="{{ post.main_image.url }}"></div>
应为:
<div><img src="{{ post.main_image.picture.url }}"></div>
原因是您的模型Image
没有url
方法。该方法属于ImageField
,在这种情况下为picture
。