首页 > 解决方案 > 为什么使用 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 %}

任何想法 ?

标签: djangodjango-viewsdjango-templates

解决方案


urls.py您忘记在文件中定义的 app_name 标签前面加上 url

def get_absolute_url(self):
    return reverse("allpost:post_detail", kwargs={'slug': self.slug}

推荐阅读