3

I'm trying to use Jinja2 templating language with Django. While trying to render a template I got the error "jinja2.exceptions.UndefinedError: 'url_for' is undefined". 'url_for()' works absolutely fine when used with templates in Flask Applications.

The template looks like this:

{% extends "login_auth/base.html" %}
{% block title %} ProjectName {% endblock %}
{% block style %} 
    <link rel="stylesheet" href="{{url_for('static/login_auth', filename='index_stl.css')}}">    
    <script src="{{ url_for('static/login_auth', filename='index.js') }}"></script>
{% endblock %}

The Traceback is as follows:

File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/ParserMouth/folder1/folder2/ProjectName/ProjectName/login_auth/views.py" in index
  10.     return render(request,"login_auth/index.html")  # index.html will be welcome screen

File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/shortcuts.py" in render
  36.     content = loader.render_to_string(template_name, context, request, using=using)

File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/template/loader.py" in render_to_string
  62.     return template.render(context, request)

File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/template/backends/jinja2.py" in render
  71.         return self.template.render(context)

File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/jinja2/asyncsupport.py" in render
  76.             return original_render(self, *args, **kwargs)

File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/jinja2/environment.py" in render
  1008.         return self.environment.handle_exception(exc_info, True)

File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/jinja2/environment.py" in handle_exception
  780.         reraise(exc_type, exc_value, tb)

File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/jinja2/_compat.py" in reraise
  37.             raise value.with_traceback(tb)

File "/home/ParserMouth/folder1/folder2/ProjectName/ProjectName/login_auth/jinja2/login_auth/index.html" in top-level template folder2
  1. {% extends "login_auth/base.html" %}

File "/home/ParserMouth/folder1/folder2/ProjectName/ProjectName/login_auth/jinja2/login_auth/base.html" in top-level template folder2
  12.         {% block style %} {% endblock %}    

File "/home/ParserMouth/folder1/folder2/ProjectName/ProjectName/login_auth/jinja2/login_auth/index.html" in block "style"
  4.     <link rel="stylesheet" href="{{ url_for('static/login_auth', filename='index_stl.css') }}">

Exception Type: UndefinedError at /
Exception Value: 'url_for' is undefined

I want to know how to solve this problem. Thanks in advance.

1
  • @VoteCoffee sir this question is specific to django. Commented Apr 2, 2021 at 8:32

3 Answers 3

3

I figured out answer for my question. The problem occurred because 'url_for' function is provided by Flask and not Jinja2. So You need to do a little bit of configuration to load static files in your templates. 1. Add jinja2.py in Project's default app and add following code in it:

from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reversefrom jinja2 import Environmentdef environment(**options):
    env = Environment(**options)
    env.globals.update({
        ‘static’: staticfiles_storage.url,
        ‘url’: reverse,
    })
 return env
  1. After this you need to replace:
<link rel="stylesheet" href="{{url_for('static/login_auth', filename='index_stl.css')}}">    
<script src="{{ url_for('static/login_auth', filename='index.js') }}"></script>

with this:

<link rel=”stylesheet” href="{{ static('login_auth/index.css') }}">
<script src="{{ static('login_auth/index.js') }}"></script>

Reference:Using Jinja2 with Django

Sign up to request clarification or add additional context in comments.

3 Comments

im facing same error on flask while rendering jinja2. it gives url_for undefined. any idea about flask?
@Harley check whether you are importing static files and have jinja2 configured properly in your virtualenv. As far as I can say you should not face this issue as you're using flask and not django.
@AzamAbbasi hopefully you have found the answer by now but in case someone is looking for flask version then, while rendering the template you can pass url_for of flask. e.g. env.get_template('xyz.html').render(url_for=url_for)
1

i think you have imported

from jinja2 import Environment
from jinja2.loaders import FileSystemLoader

font-end if looking for {{ url_for() }} in jinja2 where it is not available

try to resolve it using back-end logic like:

csslink = url_for('static/login_auth', filename='index_stl.css')
jslink = url_for('static/login_auth', filename='index.js')

return tmpl.render(csslink = csslink, jslink = jslink )

and on front-end

<link rel="stylesheet" href="{{ csslink }}">    
<script src="{{ jslink }}"></script>

Comments

-2

I think you are looking for the URL filter

if you have this in your urls :

path('client/<int:id>/', app_views.client, name='app-views-client')

you can call it this way :

{% url 'app-views-client' client.id %}

info : https://docs.djangoproject.com/fr/2.2/ref/templates/builtins/#url

3 Comments

Sir, as I have mentioned in my question I'm using Jinja2 templating in my project, not django's default template. I'm using "url_for" to load my static file in my template and not trying to link to get url for a view in django app.
my bad ! Can you try something similar to this : {{url(‘app-views-client’, args=[client.id])}} or {{url('app-views-client', kwargs={'id':client.id}}}
Ya sure. I'll try and revert back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.