cannot manipulate a dictionary data from Django inside the template - html

in my view.py:
from django.shortcuts import render
# Create your views here.
def home(req):
a={'a':1,'c':5}
return render(req,'index.html',{'a':a})
in my template:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<!-----Server data----->
<body>
<p>{{a['a']}}</p>
</body>
</html>
it gives me a template error, why i can't subscript the dic?

It gives me a template error, why i can't subscript the dictionary?
Because the Django template language is restricted to not allow subscripting. This is to discourage writing business logic in the template.
If however the subscript is a string, you can access it with a dot, for example here:
<p>{{ a.a }}</p>
If you write {{ x.y }}, then Django will try to perform a subscript (so x['y']), an attribute lookup (so x.y) (and call the method with no parameters if it is a callable), and finally a numerical lookup (so x[int(y)]).
This is specified in the Variables section of the Django documentation on the template language.

Related

How do I pass variables into an html template and use them as img source

I am working on a web server.
My goal is to load an image using a base64 string and display that image on the site.
The base64 string should vary depending what variable I use to load the template.
This is my Go rendering code:
varmap := map[string]interface{}{
"username": discordTag,
"b64": "data:image/png;base64,looongstring",
}
fmt.Println("logged in!")
templates.ExecuteTemplate(w, "index.html", varmap)
This is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div>
<h1>Welcome back, {{ .username }} {{ .b64 }}</h1>
<img src="{{ .b64 }}"/>
</div>
</body>
</html>
The displaying of the username works fine and displaying the base64 string as text works fine aswell.
Displaying of Username works
Looking at the HTML the browser renders, the img src shows up as "#ZgotmplZ"
Assuming you are using the html/template package which escapes strings to prevent code injection. You can wrap your base64 dataurl in template.URL to tell the template engine that how to treat your string.
varmap := map[string]interface{}{
"username": discordTag,
"b64": template.URL("data:image/png;base64,looongstring"),
}
I should note that unless the images are very small it might be better to serve them statically rather than embedding the into the html.

Python: How to embed my python script into a webpage

I have a full website with HTML and need to add an interactive piece that I could easily write with python (or even c/c++). What can I can use/do to accomplish this? The script will take user input do some calculations and display the output. I am completely lost on where to start, any help is appreciated!
If you want to embed Python in your HTML page the you will have to use a Python based web server which will have HTML form for data input and execute provided Python code as server side script and return you the desired result.
You could start by using Django.
If you want to build a web application with python back-end, then you need to do with a web framework, like Django or Flask. Flask is more easy to use and understandable for beginning level.
Jinja2 is a popular templating engine for Python. A web templating system combines a template with a certain data source to render dynamic web pages.
Flask code:
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def home():
return render_template("home.html")
if __name__ == "__main__":
app.run(debug=True)
home.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Flask Tutorial</title>
</head>
<body>
<h1> My First Try Using Flask </h1>
<p> Flask is Fun </p>
</body>
</html>
For Run Your First App:
python3 app.py
One way would be to embed Python into a html file using <py-script> tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hello World!</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<!-- Put Python code inside the the <py-script> tag -->
<py-script>
print("Hello World!")
input("Enter your name:")
</py-script>
</body>
</html>
Another way could be to embed Python script as a child process (eg: in Node.js):
const { spawn } = require('child_process');
var child = spawn("python", ["-c",`
print("Hi")
print(int(input("Enter a number:")))
`]);
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
process.stdin.pipe(child.stdin);
child.on('exit', () => process.exit());

How to get jinja2 variables from included files

I am writing a program that should include rather long text chunks in an html-file generated through jinja2. Because of a complex macro structure, I want to structure these texts as jinja2 variables, like so:
<!DOCTYPE HTML>
{% set standard_text = "This is the standard text." %}
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
{{standard_text}}
</body>
</html>
This works fine, but since these texts can be rather long, I want to have them in separate files. So I created a file called text.html:
{% set standard_text = "This is the standard text." %}
and put it into a library called templates/standard_texts. Now I want to import it into the html file and I have tried the following:
<!DOCTYPE HTML>
{% include 'templates/standard_texts/text.html' %}
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
{{standard_text}}
</body>
</html>
However, when I run this, I get this error:
jinja2.exceptions.UndefinedError: 'standard_text' is undefined
I have also tried other methods, such as
{% from 'templates/standard_texts/text.html import standard_text %}
or
{% extends'templates/standard_texts/text.html' %}
but that does not work either. I have read through Jinja2's "Template Designer Documentation" (http://jinja.pocoo.org/docs/2.10/templates/#), but I wasn't able to find anything there either.
How is this done?
It turns out that I made very silly error when testing option number two, using from ... import. There was an unmatched single quote, and with that fixed, it works. So corrected, the document looks like this:
<!DOCTYPE HTML>
{% from 'templates/standard_texts/text.html' import standard_text %}
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
{{standard_text}}
</body>
</html>

Django rendering template variables containing HTML as plaintext, but the source has styling

I'm having an odd issue with Django 2.0.4 (which maybe isn't so odd since I'm new to it).
I have a template which I am rendering from a view, and the data passed in is a string containing HTML.
My view renders the template as so:
return render(request, 'template.html', { 'data' : data })
data.content contains HTML in the above.
In my template, I am rendering it as so:
template.html (what works):
{{ data.content|safe }}
This renders fine. However when I have this template include other templates, the HTML ceases to render correctly.
template.html (what I want):
{% include 'header.html' %}
{{ data.content|safe }}
{% include 'footer.html' %}
The above renders header.html and footer.html fine, but the data.content|safe part in between actually becomes text with no styling. If I view source it's correct HTML (real tags, classes, etc. No & l t ; funny business.), but the browser doesn't apply rendering to it. It just winds up plaintext, e.g. strong tags around a word don't make it bold, lists are just linebreaks, etc. Even though the HTML in the top and bottom templates are included correctly with displayable HTML.
The oddest part is the only HTML that is rendered correctly from that variable is hrefs. Nothing else. I think it's crazy that no other tag works. There is no CSS messing with the HTML, either.
I have also tried using {% autoescape off %} ... {% endautoescape %} with the same results.
Obviously my intention here is to have my view display an HTML page composed of multiple templates, with values distributed among them. Yet I can't even get this one variable to display correctly, let alone any others.
Thank you so much for any help.
Edit:
header.html:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
<meta name="Description" content="" />
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,600,600i,700|Open+Sans:300,400,400i,600,700|Roboto:300,400,400i,700|Arvo:400,400i,700" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="{% static "org/css/foundation.min.css" %}"/>
<link rel="stylesheet" type="text/css" href="{% static "org/css/styles.css" %}"/>
</head>
<body>
template.html:
{{ data.content|safe }}
'data.content' is the string '<strong>test</strong>'
footer.html:
</body>
</html>
The resulting view source:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
<meta name="Description" content="" />
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,600,600i,700|Open+Sans:300,400,400i,600,700|Roboto:300,400,400i,700|Arvo:400,400i,700" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="/org/css/foundation.min.css" />
<link rel="stylesheet" type="text/css" href="/org/css/styles.css" />
</head>
<body>
<strong>test</strong>
</body>
</html>
The resulting displayed HTML page is just 'test' with no strong styling.

Update a value in Django without a refresh

I am very new to web design and I need help with a problem I have at the moment. I have written a web page with the help of Django that pulls values out of a MySQL database and places them on webpage using an embedded for loop. The values in the database are constantly updated and to get the new values displayed at the moment I am simply refreshing the page. This method seems very clunky and I was wondering if there was easy way to have them update without a refresh?
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="refresh" content="0.5">
<link rel="stylesheet" href="css/style.css">
<link href="images/favicon.ico" rel="shortcut icon">
<title>Health monitor</title>
</head>
<body>
<div class="container">
<h1>Health Monitor</h1>
<h2>Temperature Data</h2>
{% for heat in temp %}
<h3>Current temperature {{ heat.hot }} </h3>
<p>You might want to call a nurse</p>
{% endfor %}
There are a couple ways, perhaps the simplest and most accessible would be to use ajax polling to request updates on an interval.
This would be done in JavaScript. Every x seconds you would make a request to your django app to see if there are any changes.