NoReverseMatch at / 实现注释选项时出错
Posted
技术标签:
【中文标题】NoReverseMatch at / 实现注释选项时出错【英文标题】:NoReverseMatch at / error when implementing a comment option 【发布时间】:2021-06-13 05:29:35 【问题描述】:我正在尝试为 django 社交媒体应用程序实现评论选项,但在 / 错误时出现 NoReverseMatch。
NoReverseMatch 在 / 未找到带有参数“(10,)”的“post-detail”的反向。尝试了 1 种模式:['post/int:pk/$']
我已阅读 What is a NoReverseMatch error, and how do I fix it? 并且我知道它似乎找不到 post_detail.html 的 url。我查了很多类似的问题,但我找不到任何对我的案子有帮助的东西。我正在关注本教程:https://towardsdatascience.com/build-a-social-media-website-with-django-feed-app-backend-part-4-d82facfa7b3
我试图改变我在 urls.py 中声明我的网址的方式,但到目前为止似乎没有任何效果。我包括了相关的 python 和 html 文件,编辑了长度。
urls.py
from django.conf.urls import url, include
from myapp import views as core_views
from django.contrib.auth.views import LoginView, LogoutView
from django.contrib import admin
urlpatterns = [
url(r'^$', core_views.PostListView.as_view(), name ='home'),
url(r'^post/<int:pk>/$', core_views.post_detail, name='post-detail']
views.py
...
@login_required
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
user = request.user
is_liked = Like.objects.filter(user=user, post=post)
if request.method == 'POST':
form = NewCommentForm(request.POST)
if form.is_valid():
data = form.save(commit=False)
data.post = post
data.username = user
data.save()
return redirect('post-detail', pk=pk)
else:
form = NewCommentForm()
return render(request, 'feed/post_detail.html','post':post, 'is_liked':is_liked, 'form':form)
...
home.html
% extends 'base.html' %
...
% for post in posts %
<div class="card card-signin my-5">
<div class="card-body">
<a href=" post.user_name.profile.get_absolute_url "></a>
<a class="text-dark" href=" post.user_name.profile.get_absolute_url "><b> post.user_name </b></a>
<br><small class="text-muted">Posted on post.date_posted </small>
<br><br>
<p class="card-text text-dark"> post.description </p>
</div>
<a href="% url 'post-detail' post.id %"></a><img class="card-img-top" src="post.pic.url" ></a>
% if post.tags %
<br>
<p class="text-danger ml-3"><b>Tags: <i> post.tags </i></b></p>
% endif %
<div class="card-footer">
<a class="btn btn-outline-info" href="% url 'post-detail' %">Comments | post.details.count </a>
</div>
</div>
% endfor %
...
models.py
...
class Post(models.Model):
description = models.CharField(max_length=255, blank=True)
pic = models.ImageField(upload_to='static/images')
date_posted = models.DateTimeField(default=timezone.now)
user_name = models.ForeignKey(User, on_delete=models.CASCADE)
tags = models.CharField(max_length=100, blank=True)
def __str__(self):
return self.description
def get_absolute_url(self):
return reverse('post-detail', kwargs='pk': self.pk)
...
最后是错误跟踪
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.1.7
Python Version: 3.9.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'pigeonpost',
'crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template myProject\backend\pigeonpost\templates\base.html, error at line 0
Reverse for 'post-detail' with arguments '(10,)' not found. 1 pattern(s) tried: ['post/<int:pk>/$']
1 : <!DOCTYPE html>
2 : <html lang="en">
3 : <head>
4 : <meta name="viewport" content="width=device-width, initial-scale=1">
5 : <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
6 : <meta charset="UTF-8">
7 : <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
8 : <meta charset="utf-8">
9 : <title>% block title %PigeonPost% endblock %</title>
10 : </head>
Traceback (most recent call last):
File "myProject\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "myProject\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response
response = response.render()
File "myProject\lib\site-packages\django\template\response.py", line 105, in render
self.content = self.rendered_content
File "myProject\lib\site-packages\django\template\response.py", line 83, in rendered_content
return template.render(context, self._request)
File "myProject\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "myProject\site-packages\django\template\base.py", line 170, in render
return self._render(context)
File "myProject\lib\site-packages\django\template\base.py", line 162, in _render
return self.nodelist.render(context)
File "myProject\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "myProject\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "myProject\lib\site-packages\django\template\loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "myProject\lib\site-packages\django\template\base.py", line 162, in _render
return self.nodelist.render(context)
File "myProject\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "myProject\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "myProject\lib\site-packages\django\template\loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "myProject\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "myProject\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "myProject\lib\site-packages\django\template\defaulttags.py", line 211, in render
nodelist.append(node.render_annotated(context))
File "myProject\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "myProject\lib\site-packages\django\template\defaulttags.py", line 446, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "myProject\lib\site-packages\django\urls\base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "myProject\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix
raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /
Exception Value: Reverse for 'post-detail' with arguments '(10,)' not found. 1 pattern(s) tried: ['post/<int:pk>/$']
任何事情都会有很大帮助!谢谢。
【问题讨论】:
【参考方案1】:首先,最后一个标签有帖子详情 URL,但没有所需的整数变量。
第二,你不应该循环浏览帖子,因为它是一个单一的对象。
第三,根据您显示的视图,没有名为“posts”的上下文变量。这是帖子。
【讨论】:
感谢您的第一句话。对于另外两个,这是因为我将它们显示在我的页面上的列表中。这都是在文件的其他部分中定义的并且可以正常工作。仅当我尝试实现注释选项时才会遇到此错误消息。 另外,这并不能解决我的问题【参考方案2】:我已经解决了我的问题! 我需要更改调用网址的方式,因为这是旧方式。
path('post/<int:pk>/', core_views.post_detail, name='post-detail')
这是正确的做法。
【讨论】:
以上是关于NoReverseMatch at / 实现注释选项时出错的主要内容,如果未能解决你的问题,请参考以下文章
NoReverseMatch at ...... in django
NoReverseMatch at / posts / post / 18 / comment / Django Error
Django NoReverseMatch at / 路径名和/或顺序是不是冲突?
NoReverseMatch at / Reverse for 'post_detail' 未找到
NoReverseMatch at /accounts/password-reset/ 用于 Django 中的密码重置
NoReverseMatch at / Reverse for 'singlepropa' 与参数 '('mens-shirt-1',)' 未找到。已尝试 1 种模式