gpt4 book ai didi

python - Django 反向错误 : NoReverseMatch

转载 作者:IT老高 更新时间:2023-10-28 21:08:10 27 4
gpt4 key购买 nike

我查看了很多不同的帖子,但它们要么使用不同版本的 django,要么似乎不起作用。这是我想要做的:

urls.py(用于整个项目):

    from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
url(r'^blog/', include('blog.urls', namespace="blog")),
url(r'^admin/', include(admin.site.urls)),
)

urls.py(特定于应用程序):

urlpatterns = patterns ('' ,
url(r'^$', views.index, name='index'),

url(r'^(?P<slug>[\w\-]+)/$', views.posts, name="postdetail"),

)

views.py:

def index(request):
posts = Post.objects.filter(published=True)
return render(request,'blog/index.html',{'posts':posts})

def posts(request, slug):
post = get_object_or_404(Post,slug=slug)
return render(request, 'blog/post.html',{'post':post})

最后是模板:

 {% block title %} Blog Archive {% endblock %}

{% block content %}
<h1> My Blog Archive </h1>
{% for post in posts %}
<div class="post">
<h2>
<a href="{% url "postdetail" slug=post.slug %}">
{{post.title}}
</a>
</h2>
<p>{{post.description}}</p>
<p>
Posted on
<time datetime="{{post.created|date:"c"}}">
{{post.created|date}}
</time>
</p>
</div>
{% endfor %}
{% endblock %}

由于某种原因,这给了我一个“无反向匹配”:“postdetail”的反向参数“()”和关键字参数“{u'slug': u'third'}”未找到。尝试了 0 个模式:[]

我已经尝试在模板中去掉 postdetail 周围的双引号,并且我还尝试通过 View 名称而不是模式名称来引用它。仍然没有运气。该文档也不是很有帮助。

非常感谢您的帮助!谢谢

最佳答案

您在包含 URL 时使用了命名空间,因此您可能需要使用 "blog:postdetail" 来反转它。

关于python - Django 反向错误 : NoReverseMatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20889242/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com