1 from django import template
2 from django.db.models import get_models
3 from django.utils.encoding import force_unicode
4 from django.utils.safestring import mark_safe
5
6 register = template.Library()
7
10 self.varname = varname
11
13 from django.db import models
14 from django.utils.text import capfirst
15 app_list = []
16 user = context['user']
17
18 for app in models.get_apps():
19
20 app_models = get_models(app)
21 if not app_models:
22 continue
23 app_label = app_models[0]._meta.app_label
24
25 has_module_perms = user.has_module_perms(app_label)
26
27 if has_module_perms:
28 model_list = []
29 for m in app_models:
30 if m._meta.admin:
31 perms = {
32 'add': user.has_perm("%s.%s" % (app_label, m._meta.get_add_permission())),
33 'change': user.has_perm("%s.%s" % (app_label, m._meta.get_change_permission())),
34 'delete': user.has_perm("%s.%s" % (app_label, m._meta.get_delete_permission())),
35 }
36
37
38
39 if True in perms.values():
40 model_list.append({
41 'name': force_unicode(capfirst(m._meta.verbose_name_plural)),
42 'admin_url': mark_safe(u'%s/%s/' % (force_unicode(app_label), m.__name__.lower())),
43 'perms': perms,
44 })
45
46 if model_list:
47
48
49 decorated = [(x['name'], x) for x in model_list]
50 decorated.sort()
51 model_list = [x for key, x in decorated]
52
53 app_list.append({
54 'name': app_label.title(),
55 'has_module_perms': has_module_perms,
56 'models': model_list,
57 })
58 context[self.varname] = app_list
59 return ''
60
62 """
63 Returns a list of installed applications and models for which the current user
64 has at least one permission.
65
66 Syntax::
67
68 {% get_admin_app_list as [context_var_containing_app_list] %}
69
70 Example usage::
71
72 {% get_admin_app_list as admin_app_list %}
73 """
74 tokens = token.contents.split()
75 if len(tokens) < 3:
76 raise template.TemplateSyntaxError, "'%s' tag requires two arguments" % tokens[0]
77 if tokens[1] != 'as':
78 raise template.TemplateSyntaxError, "First argument to '%s' tag must be 'as'" % tokens[0]
79 return AdminApplistNode(tokens[2])
80
81 register.tag('get_admin_app_list', get_admin_app_list)
82