python - 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。
解决方案
假设您的应用名称是blog 所以在您博客的 urls.py 中添加
app_name= 'blog'
并在模板使用中{% url 'blog:post_detail' pk=post.pk %}
推荐阅读
- python - 如何从 R 中的文本文件中删除行?
- powershell - 我应该如何编写 Powershell 脚本来在多个文件上执行单个程序?
- javascript - 为 img html 标签提供多个替代图像源?
- swift - NotificationCenter - 未调用 addObserver
- python - 我需要更精确的当前时间,Python 中的倒计时时钟
- mongodb - 将文档导入到 Mongo Shard Cluster 中的特定/目标分片
- etl - ETL 从文件到 MySQL 的最佳方式
- mysql - 如何查询json中不包含任何给定关键字的数据
- excel - 获取运行时 1004:使用 vlookup 时对象“_Worksheet”的方法“范围”失败
- python - IndentationError: 期望一个缩进块(在我在 IF 循环中添加“IF”后弹出)