我正在建立一个博客,我是django的新手。我想建立一个帖子展示页面,但是标签变量不能用。
urls.py
urlpatterns = [
.
.
.
path('post/<slug>/', views.post_detail, name='post_detail'),
]
views.py
.
.
.
def post_detail(request, slug):
all_posts= Post.objects.all()
this_post = Post.objects.filter(post_slug=slug)
return render(request = request,
template_name = 'blog/post_detail.html',
context = {'this_post':this_post, 'all_posts':all_posts})
.
.
.
post_detail.html
{% extends 'blog/header.html' %}
{% block content %}
<div class="row">
<div class="s12">
<div class="card grey lighten-5 hoverable">
<div class="card-content teal-text">
<span class="card-title">{{ this_post.post_title }}</span>
<p style="font-size:70%">Published {{ this_post.post_published }}</p>
<p>{{ this_post.post_content }}</p>
</div>
</div>
</div>
{% endblock %}
从现在开始谢谢你!
而不是过滤,需要带出单个对象,然后在详细视图中才会有。filer的输出将是一个列表。
this_post = Post.objects.get(post_slug=slug)
或
this_post = get_object_or_404(Post, post_slug=slug)
this_post
不是一个 Model 实例,而是一个 Queryset。Post.objects.filter()
总是返回一个 Queryset,即使只有一条记录。属性 post_title
是Post实例的属性--不是查询集的属性。
你可以选择其中之一。
get()
: Post.objects.get(post_slug=slug)
first()
到queryset。Post.objects.filter(post_slug=slug).first()
有什么区别?
get()
将返回一个实例或引发 Post.DoesNotExist
如果没有找到Post,会出现异常。filter(...).first()
将返回查询集的第一个结果(作为模型实例)或 None
如果什么都没有发现。