当前路径{% url 'post_detail' post.pk % }不匹配django中的任何错误[已关闭]

j2cgzkjk  于 2022-11-18  发布在  Go
关注(0)|答案(2)|浏览(112)

**已关闭。**此问题为not reproducible or was caused by typos。目前不接受答案。

这个问题是由一个打字错误或一个无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
上个月关门了。
这篇文章3天前被编辑并提交审查。
Improve this question
[hi我是django的新手,我在使用主键时遇到了一个问题。project name is blog project and app is blog this is my code.]这是我点击标题时的错误截图:1

#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 %}
#views.py
 from django.shortcuts import render
from django.views.generic import ListView,DetailView
from .models import Post
# Create your views here.
class BlogListView(ListView):
    model = Post
    template_name = "home.html"
class BlogDetailView(DetailView):
    model = Post
    template_name = "post_detail.html"
8ljdwjyq

8ljdwjyq1#

您有一个拼写错误:

"{% url 'post_detail/' post.pk  % }"

删除/%}结尾处的多余空格:

"{% url 'post_detail' post.pk  %}"
zysjyyx4

zysjyyx42#

一个值得尝试的解决方案

我同意gyspark的意见,但我也认为post.pk需要改为post.id。例如:

博客/模板/主页.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.id  %}">{{ post.title }}</a></h2>
    <p>{{post.body}}</p>

</div>
{% endfor %}
{% endblock content %}

博客/urls.py

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

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

但是,你是把blog. url导入到主应用程序的www.example.com文件中吗urls.py?还是主应用程序被称为“blog”?

其他提示

另一个有用的方法是向base.html添加样式块:

<!-- The rest of your code -->
<style>
{% block style %} 
{% endblock %} 
</style>
</head>

<!-- the rest of your code -->

然后在您的模板(如home.html)中,您可以按如下方式更新它:

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

    }
{% endblock %}

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

</div>
{% endfor %}
{% endblock content %}

相关问题