Django template not displaying data from database

I am running into an issue where my database is information is displaying on one template, but I want certain parts to display on another page for a blog.

When I click into physics-blog it will display my images and post title. For this, I have looped through the database. Works fine and perfectly.

But when I click into one of them and want to show {{ physicsBlog.body }} it doesn't show anything. Which I can't wrap my head around because that works just fine in the other ListView template, but not in the DetailView template.

Here is my code.

models.py

class physicsBlog(models.Model):title = models.CharField(max_length=250)blog_image = models.ImageField(null=True, blank=True)description = models.CharField(max_length=200)author = models.ForeignKey(User, on_delete=models.CASCADE)body = RichTextField(blank=True, null=True)date_created = models.DateField(auto_now_add=True)def __str__(self):return self.title + ' | ' + str(self.author)

views.py

class physicsBlogListView(ListView):model = physicsBlogtemplate_name = 'physics.html'ordering = ['-id']class physicsBlogDetailView(DetailView):model = physicsBlogtemplate_name = 'physics-blog-details.html'

urls.py

urlpatterns = [path('', views.home, name="home"),path('physics-blog', physicsBlogListView.as_view(), name="physics-blog"),path('physics-blog/<int:pk>', physicsBlogDetailView.as_view(), name="physics-blog-details"),path('crypto-blog', cryptoBlogListView.as_view(), name="crypto-blog"),path('crypto-blog/<int:pk>', cryptoBlogDetailView.as_view(), name="crypto-blog-details"),]

I'm not super familiar using these generic displays that Django provides, but from the django docs it says

While this view is executing, self.object will contain the object that the view is operating upon.

So maybe try {{ object.body }} in your template?

You can use standard way of rendering data in standard single-object view (mostly DetailView):

{{ object.body }}

But if you want to see it better, just add context_object_name variable:

class physicsBlogDetailView(DetailView):
    context_object_name = "physics_blog"
    ...

After such change in template:

{{ physics_blog.body }}

Without context_object_name it's object or object_list. I'm kinda surprised that you did ok in ListView and had problem in DetailView, because it's the same thing.

Back to Top