“Leave password blank if dont want to change” in a django admin field

Django is a complicated but useful python web-framework, comparing to light weight frameworks like Bottle, web.py. I recently switch from Bottle, making use of it’s powerful admin site to build a Email Account Management system.

An AdminSite offer interfaces to manage databases. It includes traditional authentications, permissions, data display and POST saving mechanisms, etc. , which are nasty trifles if you try implement them from scratch using bottle or other things.

Now I can build a decent system in about 100 lines code, after many many document reading and code digging, I want to share the story how I solve the problem encountered while implementing the “Leave password blank if don’t want to change it” requirement. As commonly seen in other applications when user try to update their profile.

This works, but buggy. The password field is defaultly blank. It will clean the field in the DB without processing. The problem is, by the time in the save_model method is triggered, the obj is already updated by the values from the POST request. There’s no way to get the old password value here. All I can do without changing the old password, is to skip the obj.save(). But what if I only want to update other things?

Through out the documents, I found some other places to approch the Model instance.

Firstly the django.forms.ModelForm.save method. The module instance is returned from this method (then passed to the save_model), so I inspect the object with ipdb to see if the data is updated here:

From the call stack, the setattr call to the Model changes the data. I check django/db/models/fields/__init__.py source, find that this is a Field base class, so the obvious solution is to override this method.