1

I'm working on a Django/Wagtail project. I have a very customized feature in the admin view what will delete an object when hitting Save if certain conditions are met.

I have this in my class (that is a snippet):

def save(self, *args, **kwargs):

    if condition:     
        self.delete()

    else:
        return super(MyModel, self).save(*args, **kwargs)

This works as expected. The object gets deleted, but after this I get an error page because the browser remains in the same URL /snippets/myapp/mymodel/1234/ but the object doesn't exist anymore.

I thought of two possible solutions for this.

Possible solution 1:

def save(self, *args, **kwargs):

if condition:     
    self.delete()

    #### ===== > Redirect to objects list view

else:
    return super(MyModel, self).save(*args, **kwargs)

Possible solution 2:

def save(self, *args, **kwargs):

if condition:     

    #### ===== > Don't delete and redirect to delete view (.../mymodel/1234/delete/)

else:
    return super(MyModel, self).save(*args, **kwargs)

These are the two possible solutions I thought, but I don't know how to do any of them, even after reading docs here and there.

How can I do what I'm trying to achieve?

Pablo Viacheslav
  • 873
  • 1
  • 8
  • 15
  • 3
    The proper way from the UX perspective: when the condition is met redirect the user to a view where he/she confirms the delete. Never do destructive operations implicitly and non-reversible at the same time. – Klaus D. Apr 13 '18 at 20:33
  • Good! That's what I thought, but I don't know how to redirect to delete view – Pablo Viacheslav Apr 13 '18 at 20:39
  • 2
    Well, my penny on this would be keeping the redirect out of your save of your model. There are multiple moments in your admin to perform logic depending on the situation you are in. Redirecting from your model is odd and in my opinion unexpected behavior. It's not the model's task to redirect. The admin has multiple methods to override the behavior of redirecting on add, delete, change, etc. You might have a look at the ModelAdmin.response_* methods – Nrzonline Apr 13 '18 at 21:48
  • 1
    I totally agree with @Nrzonline . Django implementa the MVC pattern. You do not have to define a redirect logics into your model. Take a look at this question for a possible solution: https://stackoverflow.com/questions/1339845/redirect-on-admin-save – floatingpurr Apr 14 '18 at 00:00

0 Answers0