在 django 管理界面中,我有一个用于显示表格的自定义选项卡。如何将表显示为 django admin 模型列表表而不是字段,但通过从模型调用方法从 admin.py 获取表的上下文。我使用 django-baton 的
baton_form_includes
在字段下方插入模板,但随后我无法将数据传递到该模板。
models.py
class MyModel(TimeStampedModel):
.
.
.
def get_custom_tab_data(self):
return OtherModel.objects.filter(
active=False
)
admin.py
@admin.register(models.MyModel)
class MyModelAdmin():
.
.
.
readonly_fields = (
"get_custom_tab_data",
)
fieldsets = (
_("Custom Tab"),
{
"fields": ("get_custom_tab_data"),
"classes": ("tab-fs-custom")
}
)
.
.
# django-baton
baton_form_includes = [("admin/custom_tab_template.html", "get_custom_tab_data", "below")]
# This was the better solution but template table should display as model admin list with custom data, so had to use baton_form_includes to inject template above field.
# def custom_tab_data(self, myModel: models.MyModel):
# if myModel.active:
# return "N/A"
# if custom_data := myModel.get_custom_tab_data()[:15]: # get 15 latest
# html_content = render_to_string(
# "admin/custom_tab_template.html",
# {"custom_data": custom_data}
# )
# return mark_safe(html_content)
@admin.display(description="Custom Tab")
def get_custom_tab_data(self, myModel: models.MyModel):
return self.custom_tab_data(account)
custom_tab_template.html
{% load i18n l10n %}
<table class="table table-stripped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>State</th>
<th>Created</th>
</tr>
</thead>
<tbody>
{% comment %} {% for data in original.get_custom_tab_data|slice:"-15:" %} {% endcomment %}
{% for data in custom_data %}
<tr>
<th>{{ data.id }}</th>
<td>{{ data.name }}</td>
<td>{{ data.state }}</td>
<td>{{ data.created }}</td>
</tr>
{% empty %}
<tr>
<th>-</th>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
{% endfor %}
</tbody>
</table
views.py:
Django视图,可以使用render函数将数据传递给模板。
from django.shortcuts import render
def my_view(request):
my_data = {'key1': 'value1', 'key2': 'value2'}
return render(request, 'my_template.html', {'my_data': my_data})
在此示例中,my_data 是一个字典,其中包含要传递给模板的数据。该字典中的键和值将可以在模板中访问。
my_template.html:
现在,在模板中,您可以使用字典中的键访问数据。
<!DOCTYPE html>
<html>
<head>
<title>My Template</title>
</head>
<body>
<h1>{{ my_data.key1 }}</h1>
<p>{{ my_data.key2 }}</p>
</body>
</html>
在此模板中,{{ my_data.key1 }} 和 {{ my_data.key2 }} 将替换为 my_data 字典中的相应值。
在 Django 模板中工作时,请记住使用适当的模板标签({{ }} 表示变量,{% %} 表示控制流)。