Reputation: 35
I’m building a blog and I’m new to django. I’m trying to build a post display page but tag variables are not working.
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 %}
Thanks from now!
Upvotes: 1
Views: 52
Reputation: 504
this_post
is not a Model instance - it's a Queryset. Post.objects.filter()
always returns a Queryset, even if there's only one record. Attribute post_title
is an attribute of Post instance - not of a queryset.
You can do either:
get()
: Post.objects.get(post_slug=slug)
first()
to the queryset:Post.objects.filter(post_slug=slug).first()
What's the difference?
get()
will return an instance or raise Post.DoesNotExist
exception if Post is not found. filter(...).first()
will return first result from queryset (as model instance) or None
, if nothing was found.Upvotes: 0
Reputation: 3392
instead of filtering, need to bring out single object then only it will be available in detail view. Output of filer will be a list.
this_post = Post.objects.get(post_slug=slug)
or
this_post = get_object_or_404(Post, post_slug=slug)
Upvotes: 1