Reputation: 522
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!
Upvotes: 12
Views: 8980
Reputation: 18721
I had a similar problem when using a custom delete view. It was fixed by adding a class variable (static variable). An extract:
# 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)
Upvotes: 0
Reputation: 3554
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.
Upvotes: 23