无法在社交网络项目中获取 post 的 DeleteView

Can't get the DeleteView of a post in a social network project

我正在用 django 构建一个简单的社交网络。

在我社交的“主页”中,我有所有用户发布的所有 post 的列表,包括作者和发布日期。在每一个post登录用户的下方,都会出现一个“删除”按钮。如果用户点击它,它应该 return 那个 post 的特定视图,并显示一条消息,如“你真的想删除这个 post 吗?”

然而,当我点击它时,代码return出现了这个错误:

NoReverseMatch at /posts/delete/7/

Reverse for 'single' with no arguments not found. 1 pattern(s) tried: ['posts/by/(?P[-\w]+)/(?P\d+)/$']

为什么在模板中删除按钮有一个 link 到 'delete' 视图函数,为什么它说它不能在没有参数的情况下为 'single' 取反?

这是我的 urls.py,里面的 urlpatterns:

url(r'^$', 
views.PostList.as_view(), 
name='all'),

url(r'new/$', 
views.CreatePost.as_view(), 
name='create'),

url(r'by/(?P<username>[-\w]+)/$', 
views.UserPosts.as_view(), 
name='for_user'),

url(r'by/(?P<username>[-\w]+)/(?P<pk>\d+)/$', 
views.PostDetail.as_view(), 
name='single'),
 
url(r'delete/(?P<pk>\d+)/$', 
views.DeletePost.as_view(), 
name='delete'),

这是我的 views.py:

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)

这是我制作删除按钮的模板:

    {% if user.is_authenticated and post.user.username == user.username %}
       
        <a href="{% url 'posts:delete'  pk=post.pk %}" title="delete" class="btn btn-simple">
            <span class="glyphicon glyphicon-remove text-danger" aria-hidden="true"></span>
            <span class="text-danger icon-label">Delete</span>
        </a>

   {% endif %}

编辑:

这是我的模板,显示 post 并询问用户 he/she 是否真的要删除它:

<h3>Do you want to delete this post?</h3>

<div class="posts">
    {% include "posts/_post.html" with post=object hide_delete=True %}
</div>

<form class="POST">
    {% csrf_token %}
    <input type="submit" value="Confirm Delete" class="btn btn-danger btn-large">
    <a href="{% url 'posts:single' username=user.username pk=object.pk %}"
    class="btn btn-simple btn-large btn-default">Cancel</a>
</form>

模型User是django的默认值models.User

注意:我之前遇到过与使用正则表达式相关的类似错误。可以找到更多详细信息 .

我正在寻找显示删除按钮的模板部分中的错误,而错误在于模板中询问用户 he/she 是否希望删除 post。

在代码段中:

<h3>Do you want to delete this post?</h3>

<div class="posts">
    {% include "posts/_post.html" with post=object hide_delete=True %}
</div>

<form class="POST">
    {% csrf_token %}
    <input type="submit" value="Confirm Delete" class="btn btn-danger btn-large">
    <a href="{% url 'posts:single' %} username=user.username pk=object.pk %}"
    class="btn btn-simple btn-large btn-default">Cancel</a>
</form>

我换了

<a href="{% url 'posts:single' %} username=user.username pk=object.pk %}"

与:

<a href="{% url 'posts:delete' pk=post.pk %}"

现在它终于将我带到 post 删除确认视图