Login

Regrouping admin models

Author:
sleytr
Posted:
January 31, 2008
Language:
Python
Version:
.96
Score:
2 (after 4 ratings)

This is modification of Django's original adminapplist template tag. You can move your models from one app to other or completely hide them with this mod.

Copy django_dir/contrib/admin/templates/admin/index.html file to your templates/admin folder, open it, then change {% load adminapplist %} to {% load custom_adminapplist %} (or whatever you named the templatetag file)

After that, write your regrouping schema to settings.py file like this;

UPDATED, now using tupples instead of dicts in APP_SCHEMA to make it more DRY.

`

APP_SCHEMA=[

(
    ['Model','List'],
    'From App',
    'To App',
),

(
    ['FlatPage'],
    'Flatpages',
    'Site Content',
),

(
    ['Product']
    'Product',
    'Shop',
),

(
    ['Site']
    'Sites',
    #We are hiding Site model by not defining a target.
),

]

`

  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
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
#
# custom_adminapplist.py 
# place to your templatetags folder
#
from django import template
from django.db.models import get_models
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
from django.conf import settings
register = template.Library()

class AdminApplistNode(template.Node):
    def __init__(self, varname):
        self.varname = varname
        self.schema=hasattr(settings, 'APP_SCHEMA') and settings.APP_SCHEMA or []

    def to_where(self, app, model):
        for itm in self.schema:
            if app==itm[1] and model in itm[0]:
                if len(itm)==3: return itm[2]
                else: return -1

    def render(self, context):
        from django.db import models
        from django.utils.text import capfirst
        app_list = []
        user = context['user']
        transporter={}

        for app in models.get_apps():
            # Determine the app_label.
            app_models = get_models(app)
            if not app_models:
                continue
            app_label = app_models[0]._meta.app_label

            has_module_perms = user.has_module_perms(app_label)

            if has_module_perms:
                model_list = []
                for m in app_models:
                    if m._meta.admin:
                        perms = {
                            'add': user.has_perm("%s.%s" % (app_label, m._meta.get_add_permission())),
                            'change': user.has_perm("%s.%s" % (app_label, m._meta.get_change_permission())),
                            'delete': user.has_perm("%s.%s" % (app_label, m._meta.get_delete_permission())),
                        }

                        # Check whether user has any perm for this module.
                        # If so, add the module to the model_list.
                        if True in perms.values():
                            model={
                                'name': force_unicode(capfirst(m._meta.verbose_name_plural)),
                                'admin_url': mark_safe(u'%s/%s/' % (force_unicode(app_label), m.__name__.lower())),
                                'perms': perms,
                                'pname': m.__name__,
                            }
                            _to=self.to_where(app_label.title(), m.__name__)
                            if not _to:
                                model_list.append(model)
                            else:
                                if _to not in transporter: transporter[_to]=[]
                                transporter[_to].append(model)

                if model_list:
                    # Sort using verbose decorate-sort-undecorate pattern
                    # instead of key argument to sort() for python 2.3 compatibility
                    decorated = [(x['name'], x) for x in model_list]
                    decorated.sort()
                    model_list = [x for key, x in decorated]

                    app_list.append({
                        'name': app_label.title(),
                        'has_module_perms': has_module_perms,
                        'models': model_list,
                    })
        if transporter:
            for app in app_list:
                if app['name'] in transporter:
                    app_list[app_list.index(app)]['models'].extend(transporter[app['name']])
        context[self.varname] = app_list
        return ''

def get_admin_app_list(parser, token):
    """
    Returns a list of installed applications and models for which the current user
    has at least one permission.

    Syntax::

        {% get_admin_app_list as [context_var_containing_app_list] %}

    Example usage::

        {% get_admin_app_list as admin_app_list %}
    """
    tokens = token.contents.split()
    if len(tokens) < 3:
        raise template.TemplateSyntaxError, "'%s' tag requires two arguments" % tokens[0]
    if tokens[1] != 'as':
        raise template.TemplateSyntaxError, "First argument to '%s' tag must be 'as'" % tokens[0]
    return AdminApplistNode(tokens[2])

register.tag('get_admin_app_list', get_admin_app_list)

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

gamesbook (on June 25, 2010):

This gives an error:

user = context['user'] on line 26

#

Please login first before commenting.