如何将 blog.models 中的 {{ post.title }} 用于 home_app 模板
How to use {{ post.title }} from blog.models into home_app template
我想使用 {{ post.title }}
和 {{ for post in object_list }}
进入我的主页模板以显示最新的 4 个帖子,我尝试导入 from blog.models import Post
,但它不起作用。我想我放错地方了。
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
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
我想使用 {{ post.title }}
和 {{ for post in object_list }}
进入我的主页模板以显示最新的 4 个帖子,我尝试导入 from blog.models import Post
,但它不起作用。我想我放错地方了。
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
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