How to use {{ post.title }} from blog.models into home_app template

378 Views Asked by At

I want to use the {{ post.title }} and {{ for post in object_list }} into my home template to show the latest 4 posts, I tried to import from blog.models import Post, but it doesn't work. I guess I'm putting it in the wrong place.

blog.models

from django.db import models
from ckeditor.fields import RichTextField

class Post(models.Model):
    title = models.CharField(max_length = 140)
    image = models.ImageField(upload_to="media", blank=True)
    body = RichTextField(config_name='default')
    date = models.DateField()

    def __str__(self):
        return self.title

home.urls

from django.urls import path

from . import views

urlpatterns = [
    path('', views.HomePageView.as_view(), name='home'),
]

home.views

from django.views.generic import TemplateView
from allauth.account.forms import LoginForm

class HomePageView(TemplateView):
    template_name = 'home/index.html'

mysite tree look like this

mysite
    home
        admin
        app
        models
        tests
        urls
        views
    blog
        admin
        app
        models
        tests
        urls
        views
1

There are 1 best solutions below

1
Alasdair On BEST ANSWER

You can override get_context_data and add the latest blog posts to the template context.

from blog.models import Post

class HomePageView(TemplateView):
    template_name = 'home/index.html'

    def get_context_data(self, **kwargs):
        context = super(HomePageView, self).get_context_data(**kwargs)
        context['object_list'] = Post.objects.order_by('-date')[:4]
        return context