首页 > 解决方案 > 如何使用 {{ post.title }} 从 blog.models 到 home_app 模板

问题描述

我想在我的主页模板中使用{{ post.title }}and{{ 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

主页.urls

from django.urls import path

from . import views

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

主页.views

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

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

mysite 树看起来像这样

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

标签: djangotemplatesimportmodels

解决方案


您可以覆盖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

推荐阅读