Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get object from PK inside Django template?

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?

like image 311
bluemoon Avatar asked Dec 13 '12 19:12

bluemoon


People also ask

What does {{ this }} mean in Django?

These are special tokens that appear in django templates. You can read more about the syntax at the django template language reference in the documentation. {{ foo }} - this is a placeholder in the template, for the variable foo that is passed to the template from a view.

How do you pass variables from Django view to a template?

Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file.

How do I access Django templates?

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.

What is with tag in Django template?

The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client.


2 Answers

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 }}
like image 99
César Avatar answered Sep 28 '22 02:09

César


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" %}
like image 43
genry Avatar answered Sep 28 '22 02:09

genry