Inside django template, I would like to get object's name using object's pk. For instance, given that I have pk of object from class A
, I would like to do something like the following:
在django模板中,我想使用对象的pk获取对象的名称。例如,假设我有来自A类的pk对象,我想做类似以下的事情:
{{ A.objects.get(pk=A_pk).name }}
How can I do this?
我怎样才能做到这一点?
13
From the docs on The Django Template Language:
来自Django模板语言的文档:
访问方法调用:
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.
因为Django故意限制模板语言中可用的逻辑处理量,所以不可能将参数传递给从模板内访问的方法调用。应在视图中计算数据,然后传递给模板进行显示。
So you see, you should be calculating this in your views.py:
所以你看,你应该在views.py中计算:
def my_view(request, A_pk):
...
a = A.objects.get(pk=A_pk)
...
return render_to_response('myapp/mytemplate.html', {'a': a})
And in your template:
在您的模板中:
{{ a.name }}
{{ a.some_field }}
{{ a.some_other_field }}
8
You can add your own tag if you want to. Like this:
如果您愿意,可以添加自己的标签。喜欢这个:
from django import template
register = template.Library()
@register.simple_tag
def get_obj(pk, attr):
obj = getattr(A.objects.get(pk=int(pk)), attr)
return obj
Then load tag in your template
然后在模板中加载标记
{% load get_obj from your_module %}
and use it
并使用它
{% get_obj "A_pk" "name" %}
2
You can't do that in Django. From the docs:
你不能在Django那样做。来自文档:
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.
因为Django故意限制模板语言中可用的逻辑处理量,所以不可能将参数传递给从模板内访问的方法调用。应在视图中计算数据,然后传递给模板进行显示。
0
It's unclear exactly what you're trying to accomplish but you should figure out how you can achieve your desired outcome in the view and send the variable or object to the template.
目前还不清楚你要完成什么,但你应该弄清楚如何在视图中实现你想要的结果并将变量或对象发送到模板。
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2012/12/13/45a6f1a046d5d1aaf56c7f87dd603d74.html。