Reputation: 128
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.
Upvotes: 2
Views: 371
Reputation: 476614
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 theget_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.
Upvotes: 1