[Solved]-DeleteView with a dynamic success_url dependent on id

23👍

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.

👤Aylen

0👍

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)
👤SaeX

Leave a comment