django - 如何使用 {{ 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
解决方案
您可以覆盖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
推荐阅读
- javascript - $('元素').show(); vs $('element').css('visibility', 'visible'):哪个更好用?
- elm - Elm 中声明的 List 类型在哪里?
- ios - UITableView 和消失的行
- node.js - 在树莓派和mongodb之间建立连接
- driver - uboot中的设备驱动
- javascript - AngularJS 在不同模块之间共享存储在控制器中的数据
- bash - ubuntu 函数,在 source 时有效,但不适用于 bash 命令
- javascript - 将 MediaRecorder blob 发送到服务器并在后端构建文件
- jquery - 输入框中只显示小数点到 2 位?
- reactjs - 超时 - 在 jest.setTimeout 指定的 5000 毫秒超时内未调用异步回调