具有依赖于id的动态success_url的DeleteView

Pet*_*nan 8 django

我有一个帖子的应用程序,每个帖子都有一个网址:

url(r'^post/(?P<id>\w+)/$', 'single_post', name='single_post'),
Run Code Online (Sandbox Code Playgroud)

在每篇文章中,我都有评论.我希望能够从帖子页面删除每条评论并返回我所在的帖子.

我有以下网址删除评论:

    url(r'^comment/(?P<pk>\d+)/delete/$', CommentDelete.as_view(),
    name='comment_delete'),
Run Code Online (Sandbox Code Playgroud)

我从之前的研究中得知,我需要覆盖get_success_url,但我不确定如何引用我刚刚发布的帖子ID.我想我需要使用kwargs,但不确定如何.我目前有这个,但它不起作用......

class CommentDelete(PermissionMixin, DeleteView):
model = Comment
def get_success_url(self): 
    return reverse_lazy( 'single_post',
        kwargs = {'post.id': self.kwargs.get('post.id', None)},)
Run Code Online (Sandbox Code Playgroud)

想法赞赏!

Fil*_*lly 14

这应该工作:

def get_success_url(self):
    # Assuming there is a ForeignKey from Comment to Post in your model
    post = self.object.post 
    return reverse_lazy( 'single_post', kwargs={'post.id': post.id})
Run Code Online (Sandbox Code Playgroud)

Django DeleteView继承自SingleObjectMixin,包含该get_object方法.