| 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()[:self.limit] |
|---|
| 16 |
else: |
|---|
| 17 |
if not self.user.isdigit(): |
|---|
| 18 |
self.user = context[self.user].id |
|---|
| 19 |
context[self.varname] = LogEntry.objects.filter(user__id__exact=self.user).select_related()[:self.limit] |
|---|
| 20 |
return '' |
|---|
| 21 |
|
|---|
| 22 |
class DoGetAdminLog: |
|---|
| 23 |
""" |
|---|
| 24 |
Populates a template variable with the admin log for the given criteria. |
|---|
| 25 |
|
|---|
| 26 |
Usage:: |
|---|
| 27 |
|
|---|
| 28 |
{% get_admin_log [limit] as [varname] for_user [context_var_containing_user_obj] %} |
|---|
| 29 |
|
|---|
| 30 |
Examples:: |
|---|
| 31 |
|
|---|
| 32 |
{% get_admin_log 10 as admin_log for_user 23 %} |
|---|
| 33 |
{% get_admin_log 10 as admin_log for_user user %} |
|---|
| 34 |
{% get_admin_log 10 as admin_log %} |
|---|
| 35 |
|
|---|
| 36 |
Note that ``context_var_containing_user_obj`` can be a hard-coded integer |
|---|
| 37 |
(user ID) or the name of a template context variable containing the user |
|---|
| 38 |
object whose ID you want. |
|---|
| 39 |
""" |
|---|
| 40 |
def __init__(self, tag_name): |
|---|
| 41 |
self.tag_name = tag_name |
|---|
| 42 |
|
|---|
| 43 |
def __call__(self, parser, token): |
|---|
| 44 |
tokens = token.contents.split() |
|---|
| 45 |
if len(tokens) < 4: |
|---|
| 46 |
raise template.TemplateSyntaxError, "'%s' statements require two arguments" % self.tag_name |
|---|
| 47 |
if not tokens[1].isdigit(): |
|---|
| 48 |
raise template.TemplateSyntaxError, "First argument in '%s' must be an integer" % self.tag_name |
|---|
| 49 |
if tokens[2] != 'as': |
|---|
| 50 |
raise template.TemplateSyntaxError, "Second argument in '%s' must be 'as'" % self.tag_name |
|---|
| 51 |
if len(tokens) > 4: |
|---|
| 52 |
if tokens[4] != 'for_user': |
|---|
| 53 |
raise template.TemplateSyntaxError, "Fourth argument in '%s' must be 'for_user'" % self.tag_name |
|---|
| 54 |
return AdminLogNode(limit=tokens[1], varname=tokens[3], user=(len(tokens) > 5 and tokens[5] or None)) |
|---|
| 55 |
|
|---|
| 56 |
register.tag('get_admin_log', DoGetAdminLog('get_admin_log')) |
|---|