Check for variable declared in child view in parent template - python

I am migrating several pages over to use our site's new template. These are legacy pages, though, so they need a couple extra global js files.
I was hoping to set a legacy flag in the child page views, and then have an if check in the master template, but this didn't seem to work.
Is there a better way to do this?
The ideal approach would mean I could simply declare the global legacy scripts in one place. I don't want to have to include them on every legacy child page, which is what we're doing now.
Parent template:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=.5"/>
<title>Title</title>
<link rel="stylesheet" href="/static/css/global.css"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<%block name="page_css" />
</head>
<body>
<!-- Body -->
<div class="bc-page-wrapper">
${self.body()}
</div>
<script type="text/javascript" src="/static/globals.js"></script>
% if legacy == 1:
<script type="text/javascript" src="/static/js/legacy.js"></script>
% endif
</body>
</html>
Legacy Page Inheriting Template:
<%
legacy = true
%>
<%inherit file="/global/ko_admin_template.html" />
<div class="legacy-container">
content here
</div>

Related

How delete a record on button click using Django?

I am trying to delete a record in a database when a yes button is clicked using django.
views.py
def deleteServer(request, server_id):
server = Server.objects.get(pk=server_id)
print(request.POST)
if request.POST.get('yesBtn'):
server.delete()
return HttpResponseRedirect('homepage')
elif request.POST.get('noBtn'):
return HttpResponseRedirect('homepage')
return render(request, 'deleteServer.html', {'value': request.POST})
deleteServer.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">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Cancella server</title>
</head>
<body>
<button onclick="document.getElementById('id01').style.display='block'"
class="w3-button">Cancella server</button>
<!-- The Modal -->
<div id="id01" class="w3-modal">
<div class="w3-modal-content">
<div class="w3-container">
<span onclick="document.getElementById('id01').style.display='none'"
class="w3-button w3-display-topright">×</span>
<p>Vuoi davvero cancellare il server selezionato?</p>
SI
NO
</div>
</div>
</div>
</body>
</html>
When I click on the yes button the record is not deleted. I thought the problem is in the deleteServer function in the file views.py.
EDIT
I printed the results of request.GET and the output is QueryDict = {}
You just have to pass the values in the GET.. Normally it's like ?key=value and if you have multiple its ?key0=value0&key1=value1
SI
NO
Note: the =True doesn't matter, It could be literally anything because in the view it just looks ~"Is key in GET" and doesn't actually look at the value itself
Edit
I completely missed that your view used request.POST.get(x)
It should use request.GET.get(x)
def deleteServer(request, server_id):
server = Server.objects.get(pk=server_id)
print('POST:', request.POST)
print('GET:', request.GET)
if request.GET.get('yesBtn'):
server.delete()
return HttpResponseRedirect('homepage')
elif request.GET.get('noBtn'):
return HttpResponseRedirect('homepage')
return render(request, 'deleteServer.html', {'value': request.POST})

Problems with Jinja not executing python code within a block

I have a basic web app - a blog - I am trying to create using Flask.
I am trying to use {{ url_for('static', filename='vendor/fontawesome-free/css/all.min.css') }} in my index.html to create a dynamic url. However, I am continually getting a GET request error because Jinja is not recognizing it as python code, and Flask is trying to create a url using the verbatim call.
Here is an example error:
"GET /%7B‌%20%7Burl_for(%22static%22,%20filename=%22vendor/bootstrap/css/bootstrap.min.css%22)%20%7D%7D HTTP/1.1" 404
The problem is not with the url_for() call or with the structure of my directory/inclusion of correct static and template folders because using
with app.test_request_context():
print(url_for('static', filename='vendor/fontawesome-free/css/all.min.css'))
in my main.py file prints the correct path.
Additionally, Jinja is properly installed and working as evidenced by the fact that {% include "header.html" %} and {% include "footer.html" %} both work because the attempts to create the urls are all in those files.
Here is my main.py
from flask import Flask,render_template, url_for
import jinja2
app = Flask(__name__)
#app.route('/')
def root():
return render_template('index.html')
with app.test_request_context():
print(url_for('static', filename='vendor/fontawesome-free/css/all.min.css'))
if __name__=='__main__':
app.run(debug=True)
Here is the relevant part of index.html
{% include "header.html"%}
<!-- Page Header -->
<header class="masthead" style="background-image: url('static/img/home-bg.jpg')">
...
</header>
<!-- Main Content -->
<div class="container">
...
</div>
{% include "footer.html"%}
Here is the footer.html :
<!-- Footer -->
<footer>
...
</footer>
<!-- Bootstrap core JavaScript -->
<script src="{‌{ url_for('static', filename='vendor/jquery/jquery.min.js') }}"></script>
<script src="{‌{ url_for('static', filename='vendor/bootstrap/js/bootstrap.bundle.min.js') }}"></script>
<!-- Custom scripts for this template -->
<script src="{‌{ url_for('static', filename='js/clean-blog.min.js') }}"></script>
</body>
</html>
Here is the header.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Clean Blog - Start Bootstrap Theme</title>
<!-- Bootstrap core CSS -->
<link href="{‌{ url_for('static', filename='vendor/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
<!-- Custom fonts for this template -->
<link href="{‌{ url_for('static', filename='vendor/fontawesome-free/css/all.min.css')}} " rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<!-- Custom styles for this template -->
<link href="{‌{ url_for('static', filename='css/clean-blog.min.css')}} " rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav">
...
</nav>
One last note, before created the dynamic urls and doing a static reference, all the CSS/JS files rendered correctly.
Edit
The following code correctly renders the url on the page.
<h1>{{url_for('static', filename='vendor/bootstrap/css/bootstrap.min.css', _external=True)}}</h1>
It's only when I wrap it as a string that it no longer picks it up as code.
In the content you've pasted in your question, there is a Unicode zero-width non-joiner character in between the two { markers in front of your Jinja expression. That is, if I copy this line from footer.html:
<script src="{‌{ url_for('static', filename='vendor/jquery/jquery.min.js') }}"></script>
And produce a hexdump from it, I see:
00000000: 2020 3c73 6372 6970 7420 7372 633d 227b <script src="{
00000010: e280 8c7b 2075 726c 5f66 6f72 2827 7374 ...{ url_for('st
00000020: 6174 6963 272c 2066 696c 656e 616d 653d atic', filename=
00000030: 2776 656e 646f 722f 6a71 7565 7279 2f6a 'vendor/jquery/j
00000040: 7175 6572 792e 6d69 6e2e 6a73 2729 207d query.min.js') }
00000050: 7d22 3e3c 2f73 6372 6970 743e 0a }"></script>.
Look at offset x10, where we see e2 80 8c; that's the UTF-8 encoding of U+200c:
>>> "\u200c".encode()
b'\xe2\x80\x8c'
If I remove those extraneous characters from your source, everything works correctly:
$ curl -s localhost:5000 | grep static
<link href="/static/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/vendor/fontawesome-free/css/all.min.css " rel="stylesheet" type="text/css">
<link href="/static/css/clean-blog.min.css " rel="stylesheet">
<header class="masthead" style="background-image: url('static/img/home-bg.jpg')">
This is a test /static/foo/bar
<script src="/static/vendor/jquery/jquery.min.js"></script>
<script src="/static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/static/js/clean-blog.min.js"></script>

How to display HTML using Python Alone in localhost

I am trying to display my html files using python alone. Such as I would python code.py and I would be able to access my html at localhost:8080
html files are static files that access each other. For example, index.html directs to contact.html and all of them access css folder.
How do I open my html files so it displays it on the webpage?
below is what I have so far.
html_file = []
with open("index.html", "r") as f:
for line in f.readlines():
html_file.append(line)
Is there way to do python code.py and when I access localhost:8000 that would show me the code? and I can access each page.
here is an example html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>title</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<header>
<img class="resize" src="./pictures/logo.png" alt="logo">
<nav>
<ul class="nav-links">
<li class="active">Home</li>
<li>Contact</li>
</ul>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script type="text/javascript">
$(document).on('click', 'ul li', function(){
$(this).addClass('active').siblings().removeClass('active')
})
</script>
</nav>
</header>
</body>
</html>
There's way to do so using the python web frameworks like Flask or Django. In a typical flask scenario your code would look like this:-
1) Install flask:-
pip install flask
2) Write your code.py like this:-
from flask import Flask, url_for
from flask import render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('hello.html')
3) Next create a templates folder inside which put your html file which I have named it to be hello.html
templates > hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>title</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<header>
<img class="resize" src="./pictures/logo.png" alt="logo">
<nav>
<ul class="nav-links">
<li class="active">Home</li>
<li>Contact</li>
</ul>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script type="text/javascript">
$(document).on('click', 'ul li', function(){
$(this).addClass('active').siblings().removeClass('active')
})
</script>
</nav>
</header>
</body>
</html>
4) Your directory structure would look like this:-
/code.py
/templates
/hello.html
5) Run python code.py and you can see your page on localhost:5000.

How to link a css file in python

I'm sending a message with HTML via Python. Now, I'd like to style it, I've tried to write the style code into the html but there are problems because curling braces {}. Can I link the css file in Python?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://fonts.googleapis.com/css?family=Lato:400,900i&display=swap" rel="stylesheet">
<link rel='stylesheet' href="css/message_style.css"> #I've a static folder
</head>
<body>
You can do both inline stylings and also insert your CSS files into your HTML from a static folder like this:
{% load static from staticfiles %} or {% load static %}
<link rel='stylesheet' href="{% static 'css/message_style.css' %}">
Note: You should load static directory before using {% static 'relative address to the file' %}, and both {% load static from staticfiles %} or {% load static %} will do the same for you but the first one is more explicit.
EDIT: If you want to send out emails and make an email template you should use inline styles and use tables, to achieve that you can check this link for more information.

Mandrill template removing form elements

I'm using the Python mandrill package 1.0.57, as a part of the mandrill add-on for my Heroku application. I attempt to add the following template:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test Title</title>
<!-- TODO styles -->
<style>
</style>
</head>
<body>
{{#each projects}}
<h3>{{this.name}}</h3>
<form>
<label for="log">Log</label>
<input type="number" id="log" name="log">
<input type="submit" value="Submit">
</form>
{{/each}}
</body>
</html>
The each loop and h3 work fine. However, I notice that upon adding the template, it has actually been modified. Specifically, the 'code' attribute of the template appears to be missing the form and input elements. The label is missing too, but its text, 'Log', is still present
This happens even if I place the elements outside of the loop. Are forms, inputs, and labels special?
Edit: I also directly tried a curl and it still modified my template.
curl -X POST -H "Content-Type: application/json" --data #test.json https://mandrillapp.com/api/1.0/templates/add.json -v
Edit 2: I guess a working workaround is to just use messages.send()

Categories