我在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
包含媒体URL和媒体根目录:
# 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 %}
但图像没有显示。。
如果我转到url host:8000/media/pictures/test_photo.jpg
,我可以看到图像,通常我可以在页面上显示图像(例如,在django markdownx字段中),但不能通过imagefieldurl。你知道吗
有什么问题吗?你知道吗
这条线:
应该是:
原因是您的模型
Image
没有url
方法。该方法属于ImageField
,在本例中是picture
。你知道吗相关问题 更多 >
编程相关推荐