gpt4 book ai didi

python - 从模板调用模型函数

转载 作者:太空宇宙 更新时间:2023-11-03 18:52:52 24 4
gpt4 key购买 nike

我正在尝试覆盖change_form.html管理模板。当我在管理区域中输入数据时,它将帮助我看到我正在输入数据的 CSV 文件中的几行。

因此,在我的change_form.html 副本中,我放置了:

<!-- First three lines of the csv we're parsing. -->
foo: {{ csv_app.csv_sample }}
<!-- end -->

在我的模型(“csv_profile”)中:

def csv_sample(self):
return "foo"

我尝试将 csv_app.csv_sample 更改为 parse_csv.csv_app.csv_sample 以及许多其他内容 - 但我没有得到任何结果。显然我做得不对 - 谁能发现我错过了什么?

最佳答案

change_form.html 用于创建新对象和更新现有对象,因此您需要确保仅显示现有对象的字段。

更便携的方法是编写一个快速模板标记,然后将模板中的 object_id 变量传递给它。

标签可以是:

from django import template

from csv_app.models import csv_profile

register = template.Library()

@register.inclusion_tag('_tag_csv_preview.html')
def csv_preview(pk):
csv = csv_profile.get(pk=pk)
return {'preview': csv.csv_sample()}

_tag_csv_preview.html 模板仅包含 {{ prevew }} (或您想要的任何其他样式)。

然后在change_form.html中:

{% load csv_app.tags %}
{% if object_id %}
{% csv_preview object_id %}
{% endif %}

您还可以使用另一个技巧 - 这要简单得多。 adminform.form.instance 将表示正在呈现表单的实例,然后您可以执行以下操作:

{% if adminform.form.instance %}
{{ adminform.form.instance.csv_sample }}
{% endif %}

关于python - 从模板调用模型函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17905711/

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