首页 > 解决方案 > 异常类型: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的过程并返回。并删除删除命令上的帖子。

标签: pythondjangodjango-templatesdjango-urls

解决方案


HTML 页面中

更改此网址

by/username=request.username/pk=post.pk

推荐阅读