Issue
When i render blogpost.html page i can't see any content in my page. Please any devloper help me. My code look like this.
My urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='Blog_home'),
path('<slug:slug>', views.blogpost, name='blogpost'),
]
my views.py
When i print blogpost function's query i got null value
from django.shortcuts import render
from django.http import HttpResponse
from blog.models import Post
# Create your views here.
def index(request):
post = Post.objects.all()
context = {'post':post}
return render(request, 'blog/bloghome.html', context)
def blogpost(request, post_id):
post = Post.objects.filter(slug=slug)
print(post)
context = {'post':post}
return render(request, 'blog/blogpost.html', context)
Template Name:- blogpost.html
{% extends 'basic.html' %}
{% block title %}Blog{% endblock title %}
{% block body %}
<div class="contaier">
<div class="row">
<div class="col-md-8 py-4">
<h2 class=" blog-post-title">{{post.title}}</h2>
</div>
</div>
</div>
{% endblock body %}
If i write like this my blogpost.html template it's work.
{% extends 'basic.html' %}
{% block title %}Blog{% endblock title %}
{% block body %}
<div class="contaier">
<div class="row">
<div class="col-md-8 py-4">
<h2 class=" blog-post-title">Django</h2>
</div>
</div>
</div>
{% endblock body %}
Solution
You're passing a queryset as a context. Your post
object contains a queryset of Post
objects, so you can't retrieve post.title
, you need either to pass only one Post
object to your template, or loop through all of your objects and then display post.title
for each of them.
You probably need the first option, so you need to change several things.
In your urls.py
, you defined your blogpost
view by blogpost(request, post_id)
whereas in your urls.py
you defined your url as
path('<slug:slug>', views.blogpost, name='blogpost')
If you want to get an id from your url, you should define it as
path('<int:post_id>', views.blogpost, name='blogpost')
And in your blogpost
view, you do
post = Post.objects.filter(slug=slug)
but your slug isn't defined because your named it post_id
.
Once again, if you want to retrieve only a post_id, you should use
post = Post.objects.get(pk=post_id)
Answered By - Balizok
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.