Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the Object in the UpdateView to pass pk for success_url

Tags:

django

I want to the user to an view which takes an pk as argument.

I want to use the self.object in the UpdateView to look up the pk and pass ist as args to the lazy_reverse at the success_url.

First of all, is there a better way to do it, and second, how do I access the Object?

like image 919
Maximilian Kindshofer Avatar asked Sep 20 '25 06:09

Maximilian Kindshofer


1 Answers

The easiest option is to add a get_absolute_url method to your model. Then the UpdateView will redirect to this, and you don't need to set success_url at all.

class MyModel(models.Model):
    ...

    get_absolute_url(self):
        return reverse('view_mymodel', args=(self.pk,))

If you don't want to do this, then you can't use success_url and reverse_lazy here, because the url changes for each view depending on the primary key.

Instead, you can use get_success_url. You can access the object with self.object.

def get_success_url(self):
    return reverse('view_mymodel', args=(self.object.pk,))
like image 145
Alasdair Avatar answered Sep 23 '25 10:09

Alasdair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!