You can use this function to change an admin option dynamically.
For example, you can add a custom callable to list_display based on request, or if the current user has required permissions, as in the example below:
class MyAdmin(admin.ModelAdmin):
    list_display = ('__unicode__', 'other_field')
    def changelist_view(self, request, extra_context=None):
        if request.user.is_superuser:
            add_dynamic_value(self, 'list_display', my_custom_callable)
        return super(MyAdmin, self).changelist_view(request, extra_context)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24  | def add_dynamic_value(instance, attr, value, index=None, cache={}):
    """
    Dynamically insert or append (in a thread safe way) 
    a value to an admin option, e.g. *list_display* or *list_filter*.
    Arguments:
        
        - instance: an *admin.ModelAdmin* instance
        - attr: a string representing the admin option to change 
          (e.g. *list_display*)
        - value: the value to append or insert
        - index: the position where to insert the new value (None: append)
    """
    key = '%d%s' % (id(instance), attr)
    if key not in cache:
       cache[key] = getattr(instance, attr)
    new_value = list(cache[key])
    if index:
        if new_value[0] == 'action_checkbox':
            index += 1
        new_value.insert(index, value)
    else:
        new_value.append(value)
    setattr(instance, attr, new_value)
 | 
More like this
- Add Toggle Switch Widget to Django Forms by OgliariNatan 1 month, 4 weeks ago
 - get_object_or_none by azwdevops 5 months, 2 weeks ago
 - Mask sensitive data from logger by agusmakmun 7 months, 2 weeks ago
 - Template tag - list punctuation for a list of items by shapiromatron 1 year, 9 months ago
 - JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 9 months ago
 
Comments
Please login first before commenting.