django - 为什么使用 get_absolute_url 函数不起作用?
问题描述
我正在尝试使用 get_absolute_url 从(post_list)获取对象(post_detail),但返回时没有对象并且仍然在同一页面(post_list)中没有错误。在views.py
:
# 使用基于函数的视图的对象列表
def post_list(request):
post_list=Post.objects.all().order_by('-created_at')
lastest=post_list.order_by('-created_at')[:4]
last_post= post_list.order_by('-created_at')[0]
context={
'allpost':post_list,
'latest':lastest,
'lastpost':last_post
}
return render(request,'post/post_list.html',context)
# Post_singl_object 使用 DetailView
class PostDetail(DetailView):
model=Post
context_object_name='post_detail'
def get_context_data(self, **kwargs):
context= super().get_context_data(**kwargs)
context['slug']=super().get_context_data(**kwargs)
return context
urls.py :
from django.urls import path
from . import views
app_name="allpost"
urlpatterns = [
path('', views.post_list),
path('<slug:slug>',views.PostDetail.as_view(),name='post_detail'),
]
在我的页面模板(post_list.html)中,我循环获取列表对象(标题、标题、图像和作者),但在我使用的链接中(
def get_absolute_url(self):
return reverse("post_detail", kwargs={'slug': self.slug}
) 重定向到发布页面,但这不起作用并且仍在同一页面(post_list)中。在post_list.html
:
{% for post in allpost %}
<a href="{{ post_detail.get_absolute_url }}" class="stretched-link">Continue reading</a>
{% endfor %}
任何想法 ?
解决方案
urls.py
您忘记在文件中定义的 app_name 标签前面加上 url
def get_absolute_url(self):
return reverse("allpost:post_detail", kwargs={'slug': self.slug}
推荐阅读
- java - HQL 中的 Envers/Audit 创建日期/时间
- css - 使用 CSS 和百分比固定宽度
- c++ - 数组赋值中的初始值设定项太多
- java - Java:格式化 XML
- powershell - 脚本块中的变量未使用 PowerShell 传递给我的其余代码
- php - PHP 扩展方法同时覆盖它
- python - 使用另一个 Pandas DataFrame 填写 Pandas DataFrame 中的 NA 值
- spring - 表单:错误消息显示在每个字段(列表)中
- mysql - 如何更改 MySQL 数据库中的 Piwik 访问 URL?
- python - Pandas 将 groupby 操作的结果保存为原始数据框中的新列