44

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.

2
  • You can overwrite save method of model. Here is example: stackoverflow.com/questions/4269605/… Commented Apr 6, 2016 at 6:40
  • Thanks Lam, but that is what I´m doing. Check my post at the beginning. The problem is not extends save, It´s to override it. My models has a primary key restriction, but the real DB doesnt (even it looks that it hasn´t sense, it has... :P). I mean, if datas pass my own check I want to forces the insert (is_valid=True maybe...) My two approaches are: overriding save (not extends it) or jump validations on the forms Commented Apr 6, 2016 at 7:22

1 Answer 1

84

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) 
Sign up to request clarification or add additional context in comments.

5 Comments

The very first thing in the docs above save_model is a warning stating it is "not for veto purposes"
I didn´t check, I guess will be the same. With that I´m extending the method. When I call the parent it will do the same which it suppose to do. Check PK restriction I deny the inserting.
Yeah. I did it. When I am trying to add a new element a primary key restriction warning appears. I override save_model, for recover fields of request in a obj and save the obj. The priamry key restriction is checked in other part. I dont know when I´m saving (save(), save_model(),...) or in validation phase (clean(), validate(),...). Any clues?
how to add a flag for commit false ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.