如何使用 {{ post.title }} 从 blog.models 到home_app模板中



我想使用{{ post.title }}{{ for post in object_list }}到我的主页模板中以显示最新的 4 个帖子,我尝试导入from blog.models import Post,但它不起作用。我想我把它放在错误的地方。

博客.模型

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

首页.网址

from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
]

首页.视图

from django.views.generic import TemplateView
from allauth.account.forms import LoginForm
class HomePageView(TemplateView):
template_name = 'home/index.html'

我的网站树看起来像这样

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

您可以覆盖get_context_data并将最新的博客文章添加到模板上下文中。

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

相关内容

最新更新