Login

Remove named field from fieldsets

Author:
dokterbob
Posted:
November 17, 2009
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

This snipped removes a specific fields from the fieldsets. This is very useful to leave a field 'out' in the admin, likewise:

def get_fieldsets(self, request, obj=None):
    fieldsets = super(BlaModelAdmin, self).get_fieldsets(request, obj)

    if not request.user.has_perm('change_blah'):
        remove_from_fieldsets(fieldsets, ('blah',))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# Django snippet 1803: http://djangosnippets.org/snippets/1803/

import logging

logger = logging.getLogger(__name__)


def remove_from_fieldsets(fieldsets, fields):
    for fieldset in fieldsets:
        for field in fields:
            if field in fieldset[1]['fields']:
                logging.debug("'%s' field found in %s, hiding." % (field, fieldset[1]['fields']))
                newfields = []
                for myfield in fieldset[1]['fields']:
                    if not myfield in fields:
                        newfields.append(myfield)
                        
                fieldset[1]['fields'] = tuple(newfields)
                logger.debug('Setting newfields to: %s' % newfields)
            
                break

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.