Django. success_url in view or get_absolute_url () in the model. How to use them correctly?

The ModelFormMixin, which is used by BaseUpdateView, get_success_url()

has a method url = self.object.get_absolute_url()

so we don't need to write success_url = reverse_lazy('blablabla')

in the view, but just define the method get_absolute_url()

in the model. But the DeletionMixin that BaseDeleteView is using doesn't do that, it needs to success_url

.

Why? Why not make these methods the same? I had to override get_success_url

DeleteView for my, so it uses get_absolute_url()

now how I want.

Or am I not working correctly with success_url

in view? Basically, I need to change the url of the model available for the ForeignKey, now I do the following:

model Child (models.Model):
    parent = models.ForeignKey (Parent)
    def get_absolute_url (self):
        return reverse ('parent-detail', kwargs = {'pk': str (self.parent.pk)})

      

How can this be done in success_url

? I cannot write self.parent.pk

in the view

+3


source to share


2 answers


How could this work for removal? How does Django redirect to a detail page for an object that no longer exists? It doesn't make any sense; this page should return 404.

I also don't understand why you think you cannot reference the parent PC in the view. You can certainly:



def get_success_url(self):
    return reverse ('parent-detail', kwargs={'pk': self.object.parent.pk})

      

+5


source


I think you are mixing a few things here. It is expected to get_absolute_url()

point to the object it is called to (an instance of Child in your case). From the docs:

Define a get_absolute_url () method to tell Django how to compute the canonical URL for the object.

The FormView's behavior should point to this URL after you've successfully edited the object. This makes sense because you usually want to show the result of the action of the user editing the action.

However, DeleteView cannot do this, since after successfully deleting the (child) object, it of course can no longer be displayed.

So, in short, don't use get_absolute_url to specify anywhere else as the canonical kind of an object ( child-detail

in your case, I think).



If you really want to reuse the code in your case, your best bet is to write a small mixin class like:

class OnSuccessShowParent(object):
    def get_success_url(self):
        child = self.get_object()
        return reverse ('parent-detail', kwargs = {'pk': str (child.parent.pk)})

      

and then add it to your general views:

class EditChild(FormView, OnSuccessShowParent):
    ...

class DeleteChild(DeleteView, OnSuccessShowParent):
    ...

      

NB: Since the object is disposed after the get_success_url () call, that's great.

+2


source







All Articles