19👍
From the docs on The Django Template Language:
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 }}
10👍
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" %}
- Django is very slow on my machine
- Django ForeignKey limit_choices_to a different ForeignKey id
- Does anyone know about workflow frameworks/libraries in Python?
- Can you declare multiple with variables in a django template?
- Passing list of values to django view via jQuery ajax call
2👍
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.
- Passing list of values to django view via jQuery ajax call
- Matplotlib: interactive plot on a web server
- Accessing form fields as properties in a django view
- Django – Import views from separate apps
- Django: how to change values for nullbooleanfield in a modelform?
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.
0👍
-
create folder named ‘templatetags’ inside the module.
-
create ‘anyname.py’ inside the templatetags
anyname.py
from django import template
from Clients.models import Client
register = template.Library()
@register.filter
def get_client_name(pk, attr):
obj = getattr(Client.objects.get(id=pk),attr)
return obj
now in the template add
{% load get_client_name from anyname %}
{{project.Client_id|get_client_name:'Name_of_client' }}
also you can check
django documentation on custom tags
- ERROR: Invalid HTTP_HOST header: '/webapps/../gunicorn.sock'
- Registered models do not show up in admin
- In Django admin, how can I hide Save and Continue and Save and Add Another buttons on a model admin?
- Is there a Django template tag that lets me set a context variable?