Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override save method of Django Admin

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.

like image 442
Elias MP Avatar asked Apr 06 '16 06:04

Elias MP


People also ask

How do I override a save in Django?

save() method from its parent class is to be overridden so we use super keyword. slugify is a function that converts any string into a slug. so we are converting the title to form a slug basically.

How do you remove save and add another Django admin?

The simplest option is to set save_as=True on the ModelAdmin . This will replace the "Save and add another" button with a "Save as new" button.

What is Save () in Django?

save() , django will save the current object state to record. So if some changes happens between get() and save() by some other process, then those changes will be lost.


1 Answers

You can overwrite save_model of ModelAdmin.

class MyAdminView(admin.ModelAdmin):     def save_model(self, request, obj, form, change):        super(MyAdminView, self).save_model(request, obj, form, change) 
like image 89
Sơn Lâm Avatar answered Oct 08 '22 15:10

Sơn Lâm