Bs Joy
Bs Joy

Reputation: 101

How I can pass a model class attribute as a context from a class based view

I want to pass the Post model's title as a context to the template from my class-based view called PostDetailView. This title context would be the title of my template. How I can do this? All the necessary codes are given below plz help.

models.py:

from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone


class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=150)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return f'{self.author}\'s Post'

views.py:

from django.shortcuts import render
from .models import Post
from django.contrib.auth.decorators import login_required
from django.views.generic import ListView, DetailView
from django.utils.decorators import method_decorator
    

@method_decorator(login_required, name='dispatch')
class PostListView(ListView):
    model = Post
    context_object_name = 'posts'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = 'Home'
        return context

class PostDetailView(DetailView):
    model = Post
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = '?'
        return context

Upvotes: 1

Views: 327

Answers (1)

Sumithran
Sumithran

Reputation: 6565

You don't have to pass the title to the context because it is already there.

In the template, you can access it with {{ object.title }}

Or

for some reason if you still wanted to override get_context_data, then you can use self.object.title,

def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     context['title'] = self.object.title
     return context

and in templates {{ title }}

Upvotes: 1

Related Questions