I’m trying to override the save_model method on a Django admin object to prevent a user from changing a certain field. However I can’t find a way to find out if the field has changed within this method.
Here’s my code so far:
def save_model(self, request, obj, form, change):
if change:
if obj.parking_location == form.cleaned_data['parking_location']:
super(MyVehiclesAdmin, self).save_model(request, obj, form, change)
else:
messages.error(request,
"The Parking Location field cannot be changed.")
The problem is both obj.parking_location, and form.cleaned_data[‘parking_location’] have the new value. (Could this be a bug in Django? It really seems like the obj should contain the pre-save values). In any case, is there another way to accomplish this?
(I’m on Django 1.2)
Firstly, this isn’t a bug, it’s the documented behaviour in Django 1.2 onwards.
From the Django 1.2 release notes:
If you want to prevent the user from editing a paticular field, a better approach might be to use the
ModelAdmin.readonly_fieldsoption.Or, you could replace the
ModelAdmin.formwith a custom form that excludes that field.Finally, to answer your question more directly, you can check whether a field has changed in the
save_modelmethod by inspectingform.changed_data. This is a list of the names of the fields which have changed.