How to get object from PK inside Django template?

大城市里の小女人 提交于 2019-12-03 17:28:21

问题


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:

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

How can I do this?


回答1:


From the docs on 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.

So you see, you should be calculating this in your 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 }}



回答2:


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" %}



回答3:


You can't do that in Django. From the docs:

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.




回答4:


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.



来源:https://stackoverflow.com/questions/13866952/how-to-get-object-from-pk-inside-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!