翻译 django 管理日志条目消息

问题描述 投票:0回答:1

我在 https://github.com/miettinj/mezzanine 中有一个小型 django 夹层应用程序它可以正确翻译管理界面,但它也应该将页面历史记录翻译为可理解的形式。 (我猜它直接来自数据库中的django_admin_log)

现在管理日志如下所示:

{
  "model": "admin.logentry",
  "pk": 2,
  "fields": {
    "action_time": "2022-11-18T08:34:03.136Z",
    "user": 1,
    "content_type": 18,
    "object_id": "1",
    "object_repr": "janes post",
    "action_flag": 2,
    "change_message": "[{\"changed\": {\"fields\": [\"Content\", \"Keywords\"]}}]"
  }
}

我如何更改它,以便它翻译“已更改”操作,保持字段名称不变并完全删除不用户友好的字符:

("[{\)

在附件中,用蓝色包围的行是正确的,用读取包围的行是当前功能。

python django mezzanine
1个回答
0
投票

可能来晚了,但我最近也有同样的问题。

首先,你首先显示一个json(这也是python中的字典),它可以很容易地在python中解析:

{
  "model": "admin.logentry",
  "pk": 2,
  "fields": {
    "action_time": "2022-11-18T08:34:03.136Z",
    "user": 1,
    "content_type": 18,
    "object_id": "1",
    "object_repr": "janes post",
    "action_flag": 2,
    "change_message": "[{\"changed\": {\"fields\": [\"Content\", \"Keywords\"]}}]"
  }
}

可以在 python 中解析它,通过将其视为 json 表示(JSON 双重解析)或字典表示,仅保留“change_message”字段:

词典:

    data = {
  "model": "admin.logentry",
  "pk": 2,
  "fields": {
    "action_time": "2022-11-18T08:34:03.136Z",
    "user": 1,
    "content_type": 18,
    "object_id": "1",
    "object_repr": "janes post",
    "action_flag": 2,
    "change_message": "[{\"changed\": {\"fields\": [\"Content\", \"Keywords\"]}}]"
  }
}

change_message = data['fields']['change_message']

print(change_message)

输出为: [{"changed": {"fields": ["Content", "Keywords"]}}]


JSON

import json

# Your JSON string
json_str = """
{
  "model": "admin.logentry",
  "pk": 2,
  "fields": {
    "action_time": "2022-11-18T08:34:03.136Z",
    "user": 1,
    "content_type": 18,
    "object_id": "1",
    "object_repr": "janes post",
    "action_flag": 2,
    "change_message": "[{\\"changed\\": {\\"fields\\": [\\"Content\\", \\"Keywords\\"]}}]"
  }
}
"""

# Parse the JSON string into a Python object
data = json.loads(json_str)

# Extract the 'change_message' field
change_message = data['fields']['change_message']

print(change_message)

输出为 [{"changed": {"fields": ["Content", "Keywords"]}}]


最终解析

现在,要么获取整个 JSON 文件,然后解析它以获取“change_message”,要么直接从 LogEntry 获取“change_message”,然后您需要进一步解析它并定义所需的显示。例如,您可以这样做:

import json

# Your JSON string
json_str = "[{\"changed\": {\"fields\": [\"Content\", \"Keywords\"]}}]"

# Parse the JSON string into a Python object
parsed = json.loads(json_str)

# Extract 'fields' from 'changed' and join with a comma
fields = ', '.join(parsed[0]['changed']['fields'])

output = f"Changed: {fields}"

print(output)

输出为:更改:内容、关键字

© www.soinside.com 2019 - 2024. All rights reserved.