1 | from django import template
|
---|
2 | from django.contrib.admin.models import LogEntry
|
---|
3 |
|
---|
4 | register = template.Library()
|
---|
5 |
|
---|
6 | class AdminLogNode(template.Node):
|
---|
7 | def __init__(self, limit, varname, user):
|
---|
8 | self.limit, self.varname, self.user = limit, varname, user
|
---|
9 |
|
---|
10 | def __repr__(self):
|
---|
11 | return "<GetAdminLog Node>"
|
---|
12 |
|
---|
13 | def render(self, context):
|
---|
14 | if self.user is None:
|
---|
15 | context[self.varname] = LogEntry.objects.all().select_related('content_type', 'user')[:self.limit]
|
---|
16 | else:
|
---|
17 | user_id = self.user
|
---|
18 | if not user_id.isdigit():
|
---|
19 | if isinstance(context[self.user], dict):
|
---|
20 | user_id = context[self.user]['id']
|
---|
21 | else:
|
---|
22 | user_id = context[self.user].id
|
---|
23 | context[self.varname] = LogEntry.objects.filter(user__id__exact=user_id).select_related('content_type', 'user')[:self.limit]
|
---|
24 | return ''
|
---|
25 |
|
---|
26 | @register.tag
|
---|
27 | def get_admin_log(parser, token):
|
---|
28 | """
|
---|
29 | Populates a template variable with the admin log for the given criteria.
|
---|
30 |
|
---|
31 | Usage::
|
---|
32 |
|
---|
33 | {% get_admin_log [limit] as [varname] for_user [context_var_containing_user_obj] %}
|
---|
34 |
|
---|
35 | Examples::
|
---|
36 |
|
---|
37 | {% get_admin_log 10 as admin_log for_user 23 %}
|
---|
38 | {% get_admin_log 10 as admin_log for_user user %}
|
---|
39 | {% get_admin_log 10 as admin_log %}
|
---|
40 |
|
---|
41 | Note that ``context_var_containing_user_obj`` can be a hard-coded integer
|
---|
42 | (user ID) or the name of a template context variable containing the user
|
---|
43 | object whose ID you want.
|
---|
44 | """
|
---|
45 | tokens = token.contents.split()
|
---|
46 | if len(tokens) < 4:
|
---|
47 | raise template.TemplateSyntaxError(
|
---|
48 | "'get_admin_log' statements require two arguments")
|
---|
49 | if not tokens[1].isdigit():
|
---|
50 | raise template.TemplateSyntaxError(
|
---|
51 | "First argument to 'get_admin_log' must be an integer")
|
---|
52 | if tokens[2] != 'as':
|
---|
53 | raise template.TemplateSyntaxError(
|
---|
54 | "Second argument to 'get_admin_log' must be 'as'")
|
---|
55 | if len(tokens) > 4:
|
---|
56 | if tokens[4] != 'for_user':
|
---|
57 | raise template.TemplateSyntaxError(
|
---|
58 | "Fourth argument to 'get_admin_log' must be 'for_user'")
|
---|
59 | return AdminLogNode(limit=tokens[1], varname=tokens[3], user=(len(tokens) > 5 and tokens[5] or None))
|
---|