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
进行该过程并返回。并删除命令后的帖子。
答案 0 :(得分:0)
在 HTML页面
中更改此URL
by/username=request.username/pk=post.pk