cristian
cristian

Reputation: 526

Build HTML from Django View

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

Upvotes: 1

Views: 1265

Answers (3)

Tono Kuriakose
Tono Kuriakose

Reputation: 896

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

Upvotes: 0

Nikolas Stevenson-Molnar
Nikolas Stevenson-Molnar

Reputation: 4720

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()))

Upvotes: 1

colonelrascals
colonelrascals

Reputation: 378

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/'

Upvotes: 0

Related Questions