Thursday, December 5, 2013

Context Based Drop Down list - Django Admin

Problem : We have a django admin forms with Department and Employee models ,where a Department is a Foreign Key to each employee ( Each employee belongs to one department) . In one scenario we want  to edit a department , and while editing the department model we want to see  only those Employees in the drop down list having relevance to the department / model being edited. So the use case will be
  1. List of Department to edit.
  2. Click Department and Department page opens
  3. Here only the Employees applicable to the department being edited and not the super set.  Normally django will show all the objects linked to the Model and not only the ones linked to the one being edited
Solution: Overide the formfield_for_foreignkey function in admin.py under DepartmentAdmin. Most of the example like the one in django official tutorial shows how one can select things based on the logged in user , but how about selecting things based on Model being edited ?  So lets override the "formfield_for_foreignkey" for populating the employees based on the department being edited, as django shows the id or primary key of the object being edited in the request path , we will get this id and filter the records based on the this id;
Now when we edit we will see only the employees relevant to the department we are editing. ....With this we are good to go !