Syntax error whenever I put Python code inside a Django template

I'm trying to do the following in my Django template:

    {% for embed in embeds %}
           {% embed2 = embed.replace("&lt;", "<") %}
           {{embed2}}<br />
    {% endfor %}

However, I always get an invalid block or some syntax error when I do anything like that (by that I mean {% %} code inside a loop). Python doesn't have {} to signify "scope" so I think this might be my problem? Am I formatting my code wrong?

Edit: the exact error is: Invalid block tag: 'embed2'

Edit2: Since someone said what I'm doing is not supported by Django templates, I rewrote the code, putting the logic in the view. I now have:

embed_list = []
for embed in embeds:
    embed_list[len(embed_list):] = [embed.replace("&lt;", "<")] #this is line 35
return render_to_response("scanvideos.html", {
    "embed_list" :embed_list

However, I now get an error: 'NoneType' object is not callable" on line 35.

Asked by: Lyndon777 | Posted: 01-10-2021

Answer 1

I am quite sure that Django templates does not support that. For your replace operation I would look into different filters.

You really should try to keep as much logic as you can in your views and not in the templates.

Answered by: Maya498 | Posted: 02-11-2021

Answer 2

Django's template language is deliberately hobbled. When used by non-programming designers, this is definitely a Good Thing, but there are times when you need to do a little programming. (No, I don't want to argue about that. This has come up several times on django-users and django-dev.)

Two ways to accomplish what you were trying:

  • Use a different template engine. See Jinja2 for a good example that is fully explained for integrating with Django.
  • Use a template tag that permits you to do Python expressions. See limodou's Expr tag.

I have used the expr tag in several places and it has made life much easier. My next major Django site will use jinja2.

Answered by: Gianna450 | Posted: 02-11-2021

Answer 3

I don't see why you'd get "NoneType object is not callable". That should mean that somewhere on the line is an expression like "foo(...)", and it means foo is None.

BTW: You are trying to extend the embed_list, and it's easier to do it like this:

embed_list = []
for embed in embeds:
    embed_list.append(embed.replace("&lt;", "<")) #this is line 35
return render_to_response("scanvideos.html", {"embed_list":embed_list})

and even easier to use a list comprehension:

embed_list = [embed.replace("&lt;", "<") for embed in embeds]

Answered by: Adelaide138 | Posted: 02-11-2021

Answer 4

Instead of using a slice assignment to grow a list

embed_list[len(embed_list):] = [foo]

you should probably just do


But really you should try unescaping html with a library function rather than doing it yourself.

That NoneType error sounds like embed.replace is None at some point, which only makes sense if your list is not a list of strings - you might want to double-check that with some asserts or something similar.

Answered by: Walter145 | Posted: 02-11-2021

Answer 5

Django templates use their own syntax, not like Kid or Genshi.

You have to roll your own Custom Template Tag.

I guess the main reason is enforcing good practice. In my case, I've already a hard time explaining those special templates tags to the designer on our team. If it was plain Python I'm pretty sure we wouldn't have chosen Django at all. I think there's also a performance issue, Django templates benchmarks are fast, while last time I checked genshi was much slower. I don't know if it's due to freely embedded Python, though.

You either need to review your approach and write your own custom templates (more or less synonyms to "helpers" in Ruby on Rails), or try another template engine.

For your edit, there's a better syntax in Python:

embed_list.append(embed.replace("&lt;", "<"))

I don't know if it'll fix your error, but at least it's less JavaScriptesque ;-)

Edit 2: Django automatically escapes all variables. You can enforce raw HTML with |safe filter : {{embed|safe}}.

You'd better take some time reading the documentation, which is really great and useful.

Answered by: Fenton965 | Posted: 02-11-2021

Similar questions

python - The ${'foo %(a)s bar %(b)s' % {'a': '1', 'b': '2'}} syntax doesn't work in a Mako template

In a Mako template, I need to do something like: ${'foo %(a)s bar %(b)s' % {'a': '1', 'b': '2'}} When A do that, I get this error: SyntaxException: (SyntaxError) unexpected EOF while parsing (, line 1) ("'foo %(a)s bar %(b)s' % {'a': '1', 'b': '2'") in file…

python - How to access the user profile in a Django template?

I'm storing some additional per-user information using the AUTH_PROFILE_MODULE. We can access the user in a Django template using {{ request.user }} but how do we access fields in the profile since the profile is only accessible via a function user.get_profile()...

web - How can I provide safety template for user to modify with python?

I am building a multi-user web application. Each user can have their own site under my application. I am considering how to allow user to modify template without security problem? I have evaluated some python template engine. For example, genshi, it is a pretty wonderful template engine, but however it might be dangerous to allow user to modify genshi template. It have a syntax like this: &lt;?python ?&gt;...

python - What does "|" sign mean in a Django template?

I often see something like that:|escape something is an object, property is it's string property. escape - i don't know :) What does this mean? And what min python version it is used in? EDIT: The question was asked wrongly, it said "What does | mean in Python", so the bitwise or answers are correct, but irrelevant, please do ...

python - Specifying different template names in Django generic views

I have the code in my for my generic views; infodict = { 'queryset': Post.objects.all(), 'date_field': 'date', 'template_name': 'index.html', 'template_object_name': 'latest_post_list', } urlpatterns += patterns('django.views.generic.date_based', (r'^gindex/$', 'archive_index', infodict), ) So going to the address /gindex/ will use a generic view with the template of 'index.html'....

python - Django Template if tag not working under FastCGI when checking bool True

I have a strange issue specific to my Django deployment under Python 2.6 + Ubuntu + Apache 2.2 + FastCGI. If I have a template as such: {% with True as something %} {%if something%} It Worked!!! {%endif%} {%endwith%} it should output the string "It Worked!!!". It does not on my production server with mod_fastcgi. This works perfectly when I run locally with run...

python - using "range" in a google app engine template for - loop

i've got an appengine project and in my template i want to do something like {% for i in range(0, len(somelist)) %} {{ somelist[i] }} {{ otherlist[i] }} {% endfor %} i've tried using 'forloop.counter' to access list items too, but that didn't work out either. any suggestions? regards, mux

python - "x Days ago' template filter in Django?

I'm looking for a filter that turns a datetime instance into 'x Days' or 'x years y months' format (as on SO). Suggestions? Am I overlooking something very obvious?

How do I call template defs with names only known at runtime in the Python template language Mako?

I am trying to find a way of calling def templates determined by the data available in the context. Edit: A simpler instance of the same question. It is possible to emit the value of an object in the context: # in python ctx = Context(buffer, website='') # in mako &lt;%def name="body()"&gt; I visit ${website} all the time. &lt;/%def&gt; P...

python - Template driven feed parsing

Requirements: I have a Python project which parses data feeds from multiple sources in varying formats (Atom, valid XML, invalid XML, CSV, almost-garbage, etc...) and inserts the resulting data into a database. The catch is the information required to parse each of the feeds must also be stored in the database. Current solution: My previous solution was to store s...

python - how to use french letters in a django template?

I have some french letters (é, è, à...) in a django template but when it is loaded by django, an UnicodeDecodeError exception is raised. If I don't load the template but directly use a python string. It works ok. Is there something to do to use unicode with django template?

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python