- November 20, 2012
- filter admin change_list
- 2 (after 2 ratings)
When saving an edit to an object from a filtered list view you are, by default, returned to list view without any of your filters applied.
This solves that problem, keeping the filtered view in a session variable until you reach a point where the session key is deleted.
This solution doesn't require changes to template code...this is completely self contained within your own admin.py files.
The solution presented here is a revision of a previous patch, which has been modified for Django 1.4. The Django 1.3 version exists at: http://djangosnippets.org/snippets/2531/
The advantage to our solution over the above linked solution is that under different use cases the user may or may not be redirected to the filtered list_view. For example, if you edit an object and click the save and continue button, then you would lose the filter when you finally finished editing the object and clicked save.
Added on here is a delete of the session key when users add objects, the reasoning we're going this route is we don't want to return users to filtered views when they just added a new object. Your mileage may vary and if so, it's easy enough to fit your own needs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
class LocationAdmin(admin.ModelAdmin): def add_view(self, request, *args, **kwargs): result = super(LocationAdmin, self).add_view(request, *args, **kwargs ) """ Delete the session key, since we want the user to be directed to all listings after a save on a new object. """ request.session['filtered'] = None return result """ Used to redirect users back to their filtered list of locations if there were any """ def change_view(self, request, object_id, form_url='', extra_context=None): """ save the referer of the page to return to the filtered change_list after saving the page """ result = super(LocationAdmin, self).change_view(request, object_id, form_url, extra_context ) # Look at the referer for a query string '^.*\?.*$' ref = request.META.get('HTTP_REFERER', '') if ref.find('?') != -1: # We've got a query string, set the session value request.session['filtered'] = ref if request.POST.has_key('_save'): """ We only kick into action if we've saved and if there is a session key of 'filtered', then we delete the key. """ try: if request.session['filtered'] is not None: result['Location'] = request.session['filtered'] request.session['filtered'] = None except: pass return result
More like this
- keeping filter states after edits by chronosllc 3 years, 11 months ago
- Admin page without inlines dinamically by davmuz 3 years, 1 month ago
- Return to a filtered changelist on change form save by richardbolt 4 years, 12 months ago
- Complex Formsets by smagala 6 years, 6 months ago
- Custom change_list filter based on SimpleListFilter shows only referenced (related, used) values by darklow 2 years, 6 months ago