gpt4 book ai didi

mysql - 尝试制作 Django/Mezzanine "Page last updated by on date"

转载 作者:行者123 更新时间:2023-11-29 12:35:20 26 4
gpt4 key购买 nike

我正在尝试在我的夹层网站页面底部创建一个 “页面上次更新者(用户名)”于(日期)” 行。我已成功获取日期部分语法:

{{ page.updated|date:"M d, Y" }}

但用户名似乎更复杂。我在 django_admin_log 中有一个很好的列表,其中包含 action_timeuser_idobject_id,我可以从内部访问和显示 object_id我的模板使用 {{ page.id }}.

用户名位于 auth_user 中,在过去,我会在 user_id 上输入一些带有良好表连接的 SQL 来检索此信息并显示它。

我似乎无法正确理解语法 - 这种事情看起来很有希望:

page.objects.raw("select id, title from page")

但无论我如何尝试使用 {{ xxx }} 或 {% xxx %} 将其按摩到我的 base.html 中,我似乎总是得到一个错误。

谢谢各位指点

最佳答案

我找到了一种方法来做到这一点:

我创建了一个自定义标签,保存在/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 %}

希望这对某人有帮助,我很想听听是否有更简单/更优雅的方法来做到这一点!

关于mysql - 尝试制作 Django/Mezzanine "Page last updated by on date",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26870294/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com