首页 > 解决方案 > django 2.0.7 NoReverseMatch 在 /posts

问题描述

未找到“post_detail”的反向。'post_detail' 不是有效的视图函数或模式名称。

Django 到 2.0.7 之后,我设置了一些 url 规则。它在我的计算机上的 127.0.0.1 本地工作,但不能在机器上远程工作(ubuntu 1604)。

代码:post_list.html:

{% for post in posts %}
<div>
    <p>published: {{ post.published_date }}</p>
    <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1>
    <p>{{ post.text|linebreaksbr }}</p>
</div>
{% endfor %}

博客网址:

urlpatterns = [
    path('', views.home_page, name='home_page'),
    path('posts', views.post_list, name='post_list'),
    path('post/<pk>/', views.post_detail, name='post_detail'),
]

blog.views:

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

mysite.urls:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
]

解决了。我需要在 blog.url 中添加“博客”作为我的 app_name,并在 mysite.url 中添加“博客”作为我的命名空间

谢了,兄弟们!

在 2.0.7 中,我需要在 blog.url 中添加一个 app_name(博客),并在 mysite.url(博客)中添加一个命名空间。仅在 mysite.url 中添加命名空间而不在 blog.url 中添加 app_name -> django 会告诉我添加应用程序名称。仅在 blog.url 中添加 app_name 而不在 mysite.url -> django 中添加命名空间会告诉我 blog 是未注册的命名空间。还记得刷新gunicorn。

标签: pythondjangoamazon-ec2ubuntu-16.04

解决方案


假设您的应用名称是blog 所以在您博客的 urls.py 中添加

app_name= 'blog'

并在模板使用中{% url 'blog:post_detail' pk=post.pk %}


推荐阅读