Home > OS >  Dajngo template not rendering content
Dajngo template not rendering content

Time:07-22

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

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)
    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 >
    <div >
        <div >
            <h2 >{{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 >
    <div >
        <div >
            <h2 >Django</h2>
        </div>
    </div>
</div>

{% endblock body %}

CodePudding user response:

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)

CodePudding user response:

The problem is that you are not retrieving a post with this:

post = Post.objects.filter(slug=slug)

It's a queryset, which returns zero, one, or possibly >1 objects (the latter if the slugfield isn't specified unique)

Try:

post = Post.objects.get(slug=slug)

or to better handle failure

post = get_object_or_404( Post, slug=slug)

Django template language fails quietly. If something in {{ }} fails, you get a null string substituted, not a runtime error.

  • Related