python - 异常类型:NoReverseMatch
问题描述
Exception Type:NoReverseMatch
单击网站上的取消按钮时发生此错误。此取消按钮用于取消帖子的删除过程。
到处搜索但无法理解错误。还对代码进行了一些更改,但没有奏效。
path("by/<username>/<int:pk>/", views.post_detail,name='post_detail'),
views.py
def post_detail(request,pk):
post = Post.object.get(pk=pk)
comments = Comment.objects.filter(post=post)
context = {
'post':post,
'comments':comments,
}
return render(request,'posts/post_detail.html',context)
class DeletePost(LoginRequiredMixin, SelectRelatedMixin, generic.DeleteView):
model = models.Post
select_related = ("user", "group")
success_url = reverse_lazy("posts:all")
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user_id=self.request.user.id)
def delete(self, *args, **kwargs):
messages.success(self.request, "Post Deleted")
return super().delete(*args, **kwargs)
moels.py
class Post(models.Model):
title = models.CharField(max_length=255,default='')
user = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
message = models.TextField()
message_html = models.TextField(editable=False)
group = models.ForeignKey(Group, related_name="posts",null=True, blank=True,on_delete=models.CASCADE)
def __str__(self):
return self.message
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
def get_absolute_url(self):
return reverse(
"posts:post_detail",
kwargs={
"username": self.user.username,
"pk": self.pk
}
)
class Meta:
ordering = ["-created_at"]
unique_together = ["user", "message"]
post_confirm_delete.html and _post.html
{% extends "posts/post_base.html" %}
{% block post_content %}
<h3>Are you sure you want to delete this post?</h3>
<div class="posts">
{% include "posts/_post.html" with post=object hide_delete=True %}
</div>
<form method="POST">
{% csrf_token %}
<input type="submit" value="Confirm Delete" class="btn btn-danger btn-large">
<a href="{% url 'posts:post_detail' username=self.user.username pk=object.pk %}" class="btn btn-light btn-large">Cancel</a>
{% endblock %}
{% if user.is_authenticated and post.user == user and not hide_delete %}
<a href="{% url 'posts:delete' username=post.username pk=post.pk %}" title="delete" class="btn btn-simple">
<span class="fa fa-remove text-danger" aria-hidden="true"></span>
<span class="text-danger icon-label">Delete</span>
</a>
预期cancel
的过程并返回。并删除删除命令上的帖子。
解决方案
在HTML 页面中
更改此网址
by/username=request.username/pk=post.pk
推荐阅读
- validation - Semantic-ui 表单规则仅在选择选项时
- c# - 在第一列中的条件之后从 DataTable 中删除所有行
- iis - 选择 PDF 文件访问
- javascript - 如何将 JSX 导入 .tsx 文件(不在 React 中)?
- c++ - 运行调试器 Visual Studio 时 argv 中的 PATH
- c# - 如何在导入到 SQL Server 数据库时删除 Excel 电子表格的顶部行
- dask - config.yaml 中 dask 分布式 pod、worker、CPU 和 RAM 之间的关系
- mysql - 删除表A中不存在表B引用且后跟表C的记录
- cmake - 如何创建库的调试和发布版本
- python - 为 pandas 中的列使用唯一值