How to call djangos get_absolute_url method?

Question:

I am developing a web application using Django, I got started to use Class View and used the get_absolute_url method without knowing how it is triggered. I have checked Django’s documentation, unfortunately could not find nothing about that. Could someone explain? It seems that when the user is created, the get_absolute_url method is triggered automatically.

Asked By: Şahin Murat Oğur

||

Answers:

It is called by class-based views like a CreateView [Django-doc] and UpdateView [Django-doc] and other views that make use of the ModelFormMixin mixin [Django-doc].

This mixin overrides the get_success_url(..) method [Django-doc] as follows:

Determine the URL to redirect to when the form is successfully validated. Returns django.views.generic.edit.ModelFormMixin.success_url if it is provided; otherwise, attempts to use the get_absolute_url() of the object.

So if you do not provide a success_url attribute in your view, or you do not override the get_success_url method of the view yourself. Django will use the get_absolute_url() method of the object you constructed, updated, etc. in the view. This is implemented as [GitHub]:

    def get_success_url(self):
        """Return the URL to redirect to after processing a valid form."""
        if self.success_url:
            url = self.success_url.format(**self.object.__dict__)
        else:
            try:
                url = self.object.get_absolute_url()
            except AttributeError:
                raise ImproperlyConfigured(
                    "No URL to redirect to.  Either provide a url or define"
                    " a get_absolute_url method on the Model.")
        return url

The succes url is used to redirect to in case of a succesful POST request. For example the form you filled in in a CreateView is valid, and resulted in the creation of a record that the database.

Answered By: Willem Van Onsem
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.