我正在尝试在夹层网站页面的底部创建"page last updated by (username)" on (date)"
行。我已成功使用语法获得日期部分:
{{ page.updated|date:"M d, Y" }}
但用户名似乎更复杂。我在django_admin_log中有一个很好的列表,其中包含action_time
,user_id
和object_id
,我可以访问&使用{object_id
{ page.id }}.
用户名在auth_user
中,在旧的日子里,我会在user_id
上添加一个很好的表连接的SQL,以检索此信息并显示它。
我似乎无法正确使用语法 - 这种看起来很有希望:
page.objects.raw("select id, title from page")
但无论我如何尝试使用base.html
将其按到我的{{ xxx }} or {% xxx %}
,我似乎总是会出错。
感谢您的任何指示
答案 0 :(得分:1)
我找到了一种方法:
我创建了一个自定义标记,保存在/appname/templatetags/appname_tags.py中,代码如下:
from django import template
from django.db import connection
register = template.Library()
@register.inclusion_tag(‘appname/_updated_by.html')
def updated_by(pageid):
cursor = connection.cursor()
cursor.execute('select user_id from django_admin_log where object_id = %s order by id desc limit 1', [pageid])
userid_set = cursor.fetchone()
userid = userid_set[0]
cursor.execute('select first_name, last_name from auth_user where id = %s', [userid])
username = cursor.fetchone()
return {'first_name': username[0],'last_name': username[1]}
此标记通过/appname/templates/appname/_updated_by.html呈现,其中只包含:
{{ first_name }} {{ last_name }}
然后通过以下代码从base.html调用整个内容:
{% load appname_tags %}
然后在适当的位置添加:
Page Last Updated: {{ page.updated|date:"d/n/Y" }} by {% updated_by page.id %}
希望这有助于某些人,我有兴趣听听是否有更简单/更优雅的方式来做到这一点!
答案 1 :(得分:0)
您应该使用LogEntry
模型[1]。
我可能会创建一个自定义上下文处理器[2]来获取请求
Page,找到Page实例的最新LogEntry并添加updated_on
和updated_by
上下文变量。
[1] https://github.com/django/django/blob/master/django/contrib/admin/models.py#L27
[2] https://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors