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