You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django博客项目路径匹配错误:{% url 'post_detail' post.pk %}不匹配

Django主键路由匹配问题解决

问题描述

我是Django新手,在使用主键(primary key)时遇到问题。我的项目名为blog project,应用为blog,点击文章标题时出现错误:当前路径{% url 'post_detail' post.pk %}未匹配到任何路由。

错误排查与修复方案

1. 模板URL标签语法错误

你的home.html模板中,URL标签的结尾存在多余空格,导致Django解析路径出错:

<a href = "{% url 'post_detail' post.pk  % }">{{post.title}}</a>

将% }修正为%},正确写法如下:

<a href="{% url 'post_detail' post.pk %}">{{post.title}}</a>

2. 检查项目主路由配置(常见遗漏点)

确保项目根目录下的urls.py已包含blog应用的路由,添加以下配置:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),  # 必须添加此行,让Django识别blog应用的路由规则
]

修正后的完整代码

blog/urls.py

from django.urls import path
from .views import BlogListView, BlogDetailView

urlpatterns = [
    path("post/<int:pk>/", BlogDetailView.as_view(), name="post_detail"),
    path('', BlogListView.as_view(), name="home"),
]

blog/templates/home.html

{% extends 'base.html' %}
<style>
    .post-entry{ 
        color:antiquewhite;
    }
</style>

{% block content %}  
{% for post in object_list %}  
<div class="post-entry">
    <h2><a href="{% url 'post_detail' post.pk %}">{{post.title}}</a></h2>
    <p>{{post.body}}</p>
</div>
{% endfor %}
{% endblock content %}

blog/views.py

from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post

class BlogListView(ListView):
    model = Post
    template_name = "home.html"

class BlogDetailView(DetailView):
    model = Post
    template_name = "post_detail.html"

内容的提问来源于stack exchange,提问作者Yatin Lakkaraju

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 14:01:04