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

时间:2014-10-10 01:13:20

标签: django

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

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

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

我有以下用于删除评论的网址:

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

我从之前的研究中得知,我需要覆盖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)},)

赞赏的想法!

2 个答案:

答案 0 :(得分:10)

这应该有效:

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})

Django的DeleteView继承自SingleObjectMixin,其中包含get_object method

答案 1 :(得分:0)

使用自定义删除视图时遇到类似问题。它是通过添加一个类变量(静态变量)来修复的。提取物:

# Using FormView since I need to customize more than I can do with the standard DeleteView
class MyDeleteView(generic.FormView):
    person_id = 0

    def get_success_url(self):
        # I cannot access the 'pk' of the deleted object here
        return reverse('person_identity', kwargs={'person_id': self.person_id})

    def form_valid(self, form):
        plan = get_object_or_404(Plan, pk=self.kwargs['pk'])
        self.person_id = plan.person_id 
        if form.cleaned_data.get('delete', False):
            Plan.objects.filter(person=plan.person, date__gte=plan.date)\
                .filter(date__gte=datetime.date.today())\
                .delete()
        return super(MyDeleteView, self).form_valid(form)