我正在尝试使用Django框架编写一个简单的博客。我希望每个帖子都有封面图片。
我通过管理网站上传了一张图片,一切似乎都很好,但图片无法在浏览器中呈现。
这是我的档案:
models.py
(...)
class Post(models.Model):
author = models.ForeignKey('Author', on_delete=models.CASCADE)
title = models.CharField(max_length=250)
slug = models.SlugField(unique=True, blank=True, max_length=250)
created = models.DateTimeField(auto_now=False, auto_now_add=True)
modified = models.DateTimeField(auto_now=True, auto_now_add=False)
image = models.ImageField(upload_to="images/%Y/%m/", blank=True, null=True)
content = models.TextField()
(...)
django_blog_project \ urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('blog.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
博客\ urls.py
(...)
urlpatterns = [
url(r'^posts/create/$', PostCreate.as_view(), name="post_create"),
url(r'^posts/([\w-]+)/$', AuthorPostList.as_view(), name="posts_by_author"),
url(r'^(?P<slug>[-\w]+)/$', PostDetailView.as_view(), name="post_detail"),
url(r'^', PostListView.as_view(), name="post_list"),
]
settings.py
(...)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
(...)
post_detail.html
{% extends "blog/base.html" %}
{% block content %}
<h1>{{ post.title }}</h1>
<img src="{{ post.image.url }}" >
<p>{{ post.content }}</p>
<p>Autor: {{ post.author }}</p>
<p>Opublikowano: {{ post.modified }}</p>
{% endblock %}
目录树
解析为
的图片的网址<img src="/media/images/2016/12/fotolia_97812586.jpg">
答案 0 :(得分:0)
在模式中添加$
char解决了问题。
<强>博客\ urls.py 强>
(...)
urlpatterns = [
url(r'^posts/create/$', PostCreate.as_view(), name="post_create"),
url(r'^posts/([\w-]+)/$', AuthorPostList.as_view(), name="posts_by_author"),
url(r'^(?P<slug>[-\w]+)/$', PostDetailView.as_view(), name="post_detail"),
# url(r'^', PostListView.as_view(), name="post_list"), # WRONG!
url(r'^$', PostListView.as_view(), name="post_list"), # CORRECT!
]