4

I'd like to perform a check when saving a model via the django Admin panel. I thought about using ModelAdmin.save_model(), however, from the documentation it says:

ModelAdmin.save_model() and ModelAdmin.delete_model() must save/delete the object, they are not for veto purposes, rather they allow you to perform extra operations.

I need to perform a check to enforce time constraints, only if the model is being edited and in some case, I need to NOT perform the save. (e.g. If it's past midnight and the admin is trying to edit a model instance, I don't want to save the changes, and alert the admin that it's past midnight...)

What would be the best place to do that considering that ModelAdmin.save_model cannot veto the saving operation?

jeannicolas
  • 3,139
  • 4
  • 24
  • 25

3 Answers3

4

Starting with Django 1.2 you can use model validation.

jazz
  • 2,371
  • 19
  • 23
  • At that point you no longer have access to `request.user`, so it doesn't really help much depending on the validation you're trying to do. – Ariel Sep 05 '18 at 12:50
3

Simply create a modelform with normal validation via the clean methods, then assign that form to be used in the admin by doing form = MyFormClass inside the ModelAdmin class.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • I'm probably missing something obvious, but is there a safe/reliable way of knowing if the model instance is being edited, or inserted in the ModelForm's clean method? I only want to enforce validation when editing. – jeannicolas Nov 15 '11 at 17:51
  • 1
    You can check the value of self.instance.pk - if it has a value, it's an edit. – Daniel Roseman Nov 15 '11 at 18:49
0

It's not really admin site specific, but this section describes how to override the save functions on a Model, which does allow you to prevent the Model from being saved. Could be that there's a way to do what you want with this method.

EDIT:

I'm 100% speculating here, but maybe by doing something like this in admin.py you could allow it to be admin-specific.

from blah.model import * 

def newSaveFunction( self, *args, **kwargs ):
    doStuff

MyModel.save = newSaveFunction

admin.site.register(MyModel)
obmarg
  • 9,369
  • 36
  • 59