python - 如何从 Django 模板中的 PK 获取对象?

标签 python django django-templates

在 django 模板中,我想使用对象的 pk 获取对象的名称。例如,假设我有来自 A 类的对象 pk,我想执行如下操作:

{{ A.objects.get(pk=A_pk).name }}

我该怎么做?

最佳答案

来自 The Django Template Language 上的文档:

Accessing method calls :

Because Django intentionally limits the amount of logic processing available in the template language, it is not possible to pass arguments to method calls accessed from within templates. Data should be calculated in views, then passed to templates for display.

所以你看,你应该在你的 views.py 中计算这个:

def my_view(request, A_pk):
    ...     
    a = A.objects.get(pk=A_pk)    
    ...
    return render_to_response('myapp/mytemplate.html', {'a': a})

在你的模板中:

{{ a.name }}
{{ a.some_field }}
{{ a.some_other_field }}

关于python - 如何从 Django 模板中的 PK 获取对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13866952/

相关文章:

Python Django - 执行 django-admin-script.py - 打开文件而不是创建项目

c++ - Uniform Circular LBP人脸识别实现

python - 将整数列表分解为递增序列列表

Python,matplotlib pyplot show()不阻塞

python - 执行 python manage.pysyncdb 时出现 ImportError : No module named azure. storage.blob

django - 如何在 Django block 中包含模板标签

python - 在 Apache Cassandra 中混合执行两个 Python 脚本和 DatastaxBulk 加载器脚本以加载到 .csv

python - 名称 '_' 未定义

javascript - 数据表不显示表格分页

Django 模板过滤器 : apply floatformat to widthratio