How to make DjangoTemplates work recursively

42 views Asked by At

I have a template home.html which is the view of an app in Django. Now, I've added some templating in the html file to allow dynamic generation of HTML. For example I use {% load static %} and then href="{% static "path/to/resources" %}". So, when I open the app, after running the server, the path is dynamically created.

Now, the problem is that the static files, that are dynamically loaded, also need to load other static files (and extend a template as well). I thought that DjangoTemplating might be working recursively, and will work on the called file too, but sadly that is not true.

So, what should I do to make sure that all my templating logic is taken into consideration by Django, and is allowed to run?


home.html snippet:

{% load static %}
<area alt="andhra" title="Andhra Pradesh" name="andhra" href="{% static  "personal/pages/andhra.html" %}" shape="poly" ... />

andhra.html looks something like:

{% extends "personal/post.html" %}

{% blockcontent %}
  <style>
   #slider
   {
     width: 80%;
....
<div class="carousel-inner">
    <div class="carousel-item active">
        {% load static %}
        <img class="d-block w-100" src="{% static "personal/images/andhraImages/1911-1915.jpg" %}" alt="First slide">
    </div>
...
{% endblock %}

Which wants to extend the template:post.html which has {% blockcontent %}and {% endblock %} in it's body.

The andhra.html is not being template-processed. That is, when I open the app home.html is loaded correctly, but when I go to andhra.html from home.html, it isn't processed by DjangoTemplating at all.

1

There are 1 answers

0
Mooncrater On BEST ANSWER

So, as Daniel Roseman said in the comments, loading the files as a static file won't work. We want django to render them. So, I created a function state in my views.py as :

def state(request,state):
    return render(request,'personal/pages/'+state+'.html')

That means it tries to render a file at templates/personal/pages/<state>.html. Now my urls.py looks like:

urlpatterns = [
    path('',views.index,name='index'),
    path('<state>',views.state,name="state")
]

Note that this belongs to the app polls. Now, since the urls.py of mysite has polls/, thus now the link to these views will be accessible by localhost:8000/polls/<state>.

Now at every place I wanted a static link, I made a dynamic one by:

href="{% url 'state' 'uttarakhand' %}"

where 'state' is the name of the urlpattern and 'uttarakhand' is the input value.