I need to construct the HTML body from a Django view and I cannot find a solution to refer correctly a JPG file ( must say that the HTML is much larger then this, but with other stuff seems that is working for me ):
I've tried this:
from django.template import Template
...
html = Template('<IMG SRC="{% static "base/images/course/website-46-2.jpg" %}">')
return HttpResponse( html )
And I get this error:
Invalid block tag on line 1: 'static'. Did you forget to register or load this tag?
In Django template I resolve this by loading the static files:
{% load static %}
How can I do this in Python ( Django View ) ? Or any other suggestion is much appreciated.
I've tried different solution that I have found on this site and others but none seems to work for me.
Django Version: 2.2.1
-
{% extends "name" %} ?JonPizza– JonPizza2019年08月20日 16:23:06 +00:00Commented Aug 20, 2019 at 16:23
-
Don't understand this.cristian– cristian2019年08月20日 16:44:14 +00:00Commented Aug 20, 2019 at 16:44
3 Answers 3
You can create an engine with the static library as a built-in. This makes it available to the template without calling {% load static %} first.
from django.template import Template, Context, Engine
engine = Engine(builtins=['django.templatetags.static'])
template = engine.from_string('<IMG SRC="{% static "base/images/course/website-46-2.jpg" %}">')
return HttpResponse(template.render(Context()))
8 Comments
Have you set your STATIC_URL in settings.py? You can do this by the following:
STATIC_URL = '/static/'
Your image would then be found under 'your_app/static/base/images/course/website-46-2.jpg'.
Does the folder structure follow this convention? If not you can set the STATIC_URL to '/base/'
4 Comments
html = Template('{% load static %}<IMG SRC="{% static "base/images/course/website-46-2.jpg" %}">')def startchat(request):
template=loader.get_template('app1/chatbot.html')
return HttpResponse(template.render())
This function loads the html page into Django. Before that , we need to import the module
from django.template import loader