Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DeleteView with a dynamic success_url dependent on id

Tags:

django

I have an app for posts, with a url for each post:

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

On each post, I have comments. I would like to be able to delete each comment from the post page and return to the post that I was on.

I have the following url for deleting comments:

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

And I know from previous research that I need override the get_success_url, but I'm not sure how to reference the post id that I was just on. I think I need to use kwargs, but not sure how. I have this currently, but it doesn't work...

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

Ideas appreciated!

like image 681
Pete Drennan Avatar asked Oct 10 '14 01:10

Pete Drennan


1 Answers

This should work:

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's DeleteView inherits from SingleObjectMixin, which contains the get_object method.

like image 51
Aylen Avatar answered Nov 11 '22 00:11

Aylen