Override admin save method? – Add extra control to admin

//Override admin save method? – Add extra control to admin

Override admin save method? – Add extra control to admin

I need to Override admin save method, and add extra control to admin save method.

I will present you one of three available methods

What I wanted to achieve was adding some control when saving a instance of a model from the admin, because it is the only place where it is going to be modified.

There are three options:

  1. First of all : on clean and full_clean method of the model. BUT , it will be executed also when saving model from another place. PROBABLY this is also a behaviour we expect.
  2. Override save method : If you do this, you MUST save the model.
  3. Override admin form

I am going to demonstrate how to do the third one because is the one of interest for what I wanted to achieve.

The model:

RuleMethod is a model representing some rules. The code does not care, so I will not post it.

What I want, is when saving this zone model, check some things on rule.

In this example will always fail, of course. But it was for testing.

The result when saving will be :

Result of a validation error

Result of a validation error

To make some validation on a field, the key is the method clean_[field_name].

And the posted field value is self.cleaned_data['field_name'].

And you can raise a ValidationError as the example to prevent saving.

Here is another interesting link on validation: https://code.kiwi.com/django-under-the-hood-2016-validation-68cc635a07c4

A more useful example will be:

 

Happy coding!

By |2018-05-07T20:30:29+00:00mayo 3rd, 2018|Categories: Django|Tags: , |2 Comments

About the Author:

2 Comments

  1. click here julio 7, 2018 at 4:54 am - Reply

    great and good looking post here

  2. eebest8 michael junio 17, 2018 at 3:33 am - Reply

    “We stumbled over here coming from a different web address and thought I might check things out. I like what I see so now i’m following you. Look forward to looking into your web page again.”

Leave A Comment