Override save method of Django Admin

Question:

Well, I want to save any instance of a model without taking care about DDBB structure. So I decide to override def save in every model´s class. Kind of:

def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
    if condition:
        raise Exception("You can´t insert that element")
    return super(name_class, self).save(self, force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)

Well, with this I achieve to insert not raising an exception, but if the instance passes this check I want to insert in the DB whatever primary restriction exists…

How can I get it?

I suppose I must have to override the core code of save, but I checked it and I didn’t find the part where I check the conditions for inserting in the DB.
Maybe, The problem is only in the validation of the form.

How can I override a specific form in Django Admin? Specifically, that one where I add, Delete or Edit one class of the model.

Asked By: Elias MP

||

Answers:

You can overwrite save_model of ModelAdmin.

class MyAdminView(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)
Answered By: Sơn Lâm
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.