, 'single_post', nam...">

DeleteView with dynamic id_-dependent success_url

I have a messaging app with a url for each post:

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

In each post I have comments. I would like to be able to delete every comment from the mail page and return to the message I was in.

I have the following url to delete comments:

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

And I know from previous studies that I need to override get_success_url, but I'm not sure how to refer to the identifier of the message I was just on. I think I need to use kwargs, but I don’t know how to do it. I have it now, but it does not 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!

+5
source share
2 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 DeleteView inherits from SingleObjectMixin , which contains the get_object method.

+5
source

I had a similar problem when using a custom delete type. It has been fixed by adding a class variable (static variable). Exposure:

 # 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) 
0
source

Source: https://habr.com/ru/post/1204387/


All Articles