jinja2.exceptions.TemplateNotFound error when making a python virtual environment - python

so I have made a website using Flask which was working perfectly fine until today when I tried to create a python virtual environment. Does anyone know what could have happened? This is the code for my python file.
from flask import Flask, render_template
app = Flask(__name__, template_folder='html_scripts')
#app.route('/home/')
def home():
return render_template('html_scripts')
#app.route('/about/')
def about():
return render_template('html_scripts')
if __name__ == '__main__':
app.run(debug = True)
This is the code for my main html file:
<!DOCTYPE html>
<html>
<head>
<title>Flask App</title>
<link rel="stylesheet" href="{{url_for('static',filename='css/main.css')}}">
</head>
<body>
<header>
<div class="container">
<h1 class="logo">Adrian's web app</h1>
<strong><nav>
<ul class="menu">
<li>Home</li>
<li>About</li>
</ul>
</nav></strong>
</div>
</header>
<div class="container">
{%block content%}
{%endblock%}
</div>
</body>
</html>
And these are the remaining 2 files(home_page.html and about.html):
{%extends 'layout.html'%}
{%block content%}
<div class = 'home'>
<h1>My homepage</h1>
<p>This is my homepage</p>
</div>
{%endblock%}
and,
{%extends 'layout.html'%}
{%block content%}
<div class = 'about'>
<h1>My about page</h1>
<p>This is my about page</p>
</div>
{%endblock%}
Please do help if you kow how because I have not seen anyone with this problem yet and I can't solve it myself.
Thanks!

In render_template, try using the actual html files. The code below fixes your problem
from flask import Flask, render_template
app = Flask(__name__, template_folder='html_scripts')
#app.route('/home/')
def home():
return render_template('/home_page.html')
#app.route('/about/')
def about():
return render_template('/about.html')
if __name__ == '__main__':
app.run(debug = True)

If use virtual environment You must :
first active virtual environment
go to directory app.py file
run python app.py
For example: my project flask in this path D:\MyProjects\MyflaskApp first active virtualEnviorment then :
(my_env) E:\virtualEnc> cd "D:\MyProjects\MyflaskApp"
(my_env) D:\MyProjects\MyflaskApp>python app.py
* Serving Flask app '__name__'
* Debug mode: off
app.py :
app = Flask(__name__)

Related

jinja2.exceptions.UndefinedError: 'btn' is undefined

I am getting jinja2.exceptions.UndefinedError: 'btn' is undefined exception while logging to the localhost. The btn is properly defined but still.. Can I plaese get the help as soon as possible. Thank You in Advance
Python code- This code is the Python Code
from flask import Flask, render_template, request, send_file
from flask_sqlalchemy import SQLAlchemy
from send_email import send_email
from sqlalchemy.sql import func
from werkzeug import secure_filename
app=Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route("/success", methods=['POST'])
def success():
global file
if request.method=='POST':
file=request.files["file"]
file.save(secure_filename("uploaded" + file.filename))
with open("uploaded"+file.filename,"a") as f :
f.write("This was added later!")
return render_template("index.html", btn="download.html")
#app.route("/download")
def download():
return send_file("uploaded" + file.filename, attatchment_filename="yourfile.csv", as_attatchment=True)
if __name__ == '__main__':
app.debug=True
app.run()
HTML-
Index file - This is the main file
<!DOCTYPE html>
<html lang="en">
<title> Data Collector App</title>
<head>
<link href="../static/main.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Collecting Height</h1>
<h3>Please Fill the Entries to get Population Statistics on Height</h3>
<div class="message">
{{text | safe}}
</div>
<form action="{{url_for('success')}}" method="POST" enctype="multipart/form-data">
<input type="file" name="file" > <br>
<button type="submit">Submit</button>
</form>
{%include btn ignore missing%}
</div>
</body>
</html>
Download file- This is the html file for downloading. After importing the file this html code will create a button in the same index.html page so that I can also downoad the same file
<!DOCTYPE html>
<html lang="en">
<div class="download">
<button class="btn"> Download </button>
</div>
</html>
Was facing the same issue. My workaround was to replace:
{% include btn ignore missing %}
with
{% if btn %}
{% include btn %}
{% endif %}
This should work:
{% include [btn] ignore missing %}
The reason for change is due to a Flask update from the time when that video was created

jinja2.exceptions.TemplateNotFound why does this keep popping up?

This is my code pro.py which i have save in my Downloads:
from flask import Flask, render_template, flash, session, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField
app = Flask(__name__)
app.config['SECRET_KEY'] = 'kmkey'
class SimpleForm(FlaskForm):
breed = StringField('What breed are you?')
submit= SubmitField('Click Me')
#app.route('/',methods=['GET','POST'])
def imp():
form = SimpleForm()
if form.validate_on_submit():
session['breed'] = form.breed.data
flash(f"You just changed your breed to: {session['breed']}")
return redirect(url_for('imp'))
return render_template('imp.html',form=form)
if __name__ == '__main__':
app.run(debug=True)
This is my html code imp.html which i have saved in my template folder which is inside Downloads:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
{% for mess in get_flashed_messages() %}
<div class="alert alert-warning alert-dismissible fade show" role='alert'>
<button type="button" class="fade close" data-dismiss='alert' aria-label='close' >
<span aria-hidden='true'>×</span>
</button>
{{mess}}
</div>
{% endfor %}
<form method="post">
{{form.hidden_tag()}}
{{form.breed.label}}{{form.breed}}
{{form.submit()}}
</form>
</body>
</html>
Now when i run my python file on web it throws an error saying that
jinja2.exceptions.TemplateNotFound:imp.html why does it happen like that??
Can anyone pls help me out with this issue.
You need to save it in templates folder not template folder.

How to execute a python script or call a function from a pythons script using flask & wtform

Am very much new to Flask & Python, so want to understand/clear my concepts. I have a webpage which i created using flask & wtforms. Html page is very simple having just single field & a submit button. I want to call a python script (test.py) itself or python function(pythonfunction()) when submit button is clicked. Also Is there a way from the webpage,whatever i enter , i can pass as an attribute to that python script (test.py)? help appreciated
**app.py**
from flask import Flask , render_template,flash,redirect,url_for,session,logging,request
from wtforms import Form,StringField,TextAreaField,PasswordField,validators,SelectField,TextAreaField
from wtforms.widgets import TextArea
import subprocess
import test
app=Flask(__name__)
#app.route ('/')
def index():
return render_template('home.html')
class testpython(Form):
testenter=StringField('Enter something')
#app.route ('/testpage',methods=['GET','POST'])
def testpage():
form=testpython(request.form)
return render_template('testpage.html',form=form,python=testfunc(testenter))
if __name__ == '__main__':
app.run(debug=True)
**test.py**
def pythonfunctiontest (self):
print data #<something i can print here from that text field in webpage>
return "all good"
**testpage.html**
{% extends 'sec_layout.html'%}
{% block body %}
{% from "includes/_formhelpers.html" import render_field %}
<form method="POST" action ="">
<div class="form-group">
{{render_field(form.testenter,cols="1", rows="5",class_="form-control")}}
</div>
<div class="input-bar-item input-bar-item-btn">
<button class="btn btn-info">Submit</button>
</div>
</form>
{% endif %}
{% endblock%}
sec_layout.html
<!DOCTYPE <!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>MY PAGE-TEST</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
{% include 'includes/_navbar.html' %}
<div class= "container">
{% block body %}{% endblock%}
</div>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" </script>
</body>
</html>
The question is very general so I will try and give you a steer and perhaps you might revisit this question later with a little more clarity.
Flask asks a server and renders webpages. I.e. it executes some code on the server and passes it to the client web browser. The client web browser can then execute client side code (i.e. Javascript) as the user is browsing and can pass data back to the server using submit forms (to different Flask routes) or via JavaScript AJAX requests (again to other Flask routes). So if you want to execute python script based on some input you will need a separate route.
Here is a simple example of an index page and a second route that will execute something else:
#app.route('/index')
def index():
""" very basic template render """
return render_template('index.html')
#app.route('/data-submit', methods=["POST"])
def calc():
data = request.form.information.data
# do something with data..
x = data + data
return render_template('new_page.html', x)
========= (index.html)
<html>
<body>
<form action="{{ url_for('app.calc') }}" method="POST">
<input name="information" type='text'>
<button name="submit">
</form>
</body>
</html>
Wrap whatever temp.py is doing in a function.
Place it in the same directory as flask.py. Call import temp in flask.py, then use temp.myfunction().

Displaying a .txt file in my html using Python Flask

I want to display my log.txt in my log.html.
For some reason my page is completely blank.
And I dont get to see anything from my file.
Code:
def log():
with open("logs.txt", "r") as f:
content = f.read()
return render_template('log.html', content=content)
HTML LOG TEMPLATE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Log</title>
<link rel="stylesheet" href="/static/styles/nav.css" />
<link rel="stylesheet" href="/static/styles/basiclayout.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<style>
</style>
<body>
<ul class="nav">
<li ><a href="{{ url_for('hello_world') }}" >Home</a></li>
<li >Notepad</li>
<li >Explorer </li>
<li class="active">Log </li>
<li >Upload </li>
<li >Uploads </li>
<li >Logout</li>
</ul>
<div class="alert">
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %}
</div>
<pre>{{ content }}</pre>
</body>
</html>
Added my HTML Template now.
return Response(content, mimetype='text/plain')
but really you probably want to use something like logstash...
Maybe it would be better if for the log to read the file backwards in order to access the last log first.
pip3 install file-read-backwards
For example, I will show this code backwards:
In your case, it is necessary to replace app.py with logs.txt
from flask import Flask, render_template
from file_read_backwards import FileReadBackwards
app = Flask(__name__, template_folder="template")
with FileReadBackwards("app.py") as f:
# getting lines by lines starting from the last line up
b_lines = [ row for row in f ]
#app.route('/', methods=["GET", "POST"])
def index():
return render_template('index.html', b_lines=b_lines)
if __name__ == "__main__":
app.run(debug=True)
UPDATE - without libraries
from flask import Flask, render_template
app = Flask(__name__, template_folder="template")
#app.route('/', methods=["GET", "POST"])
def index():
b_lines = [row for row in reversed(list(open("app.py")))]
return render_template('index.html', b_lines=b_lines)
if __name__ == "__main__":
app.run(debug=True)
Put in your log.html:
<br>
Description:
<br>
<textarea id="stackoverflow" name="stackoverflow_review" rows="35" cols="55">
{% for line in b_lines %}
{{ line }}
{% endfor %}
</textarea>
output:
In your case, the latest changes from the logs.txt file will be displayed first.
There are two files one being "file.py" and the respective HTML file being invoked from the templates folder.
import sys
from flask import Flask, render_template, redirect, url_for, request
app = Flask(__name__, template_folder="/root/templates")
def search():
with open("test","r") as file:
content = file.readlines()
print(content)
return render_template("file2.html", content = content)
if __name__ == "__main__":
app.run(debug=True)
File2.html:
Not sure how to attach HTML file. attaching a screen shot . Please refer

flask isnt reading or interpreting css file

I'm basically trying to follow this tutorial ( http://net.tutsplus.com/tutorials/python-tutorials/an-introduction-to-pythons-flask-framework/)
Now when the css part comes in, and i copy the code it simply wont come out styled even afterr main.css is added it still shows up unstyled like if it wasn't importing the css file here's the HTML code
<!DOCTYPE html>
<html>
<head>
<title>Flask</title>
<strong><link rel="stylesheet" type"text/css" href="{{ url_for('static', filename='css/main.css') }}"></strong>
</head>
<body>
<header>
<div class="container">
<h1 class="logo">Flask App</h1>
</div>
</header>
<div class="container">
{% block content %}
{% endblock %}
</div>
</body>
</html>
layout.html ^
Home.html v
{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>Welcome to the Flask app<h2>
<h3>This is the home page for the Flask app<h3>
</div>
{% endblock %}
routes.py v
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)
This is probably due to the directory structure of your app. By default, flask looks for the static directory in the same level as the file that the app object is created in. This is the example structure for a small application from the flask docs.
/yourapplication
/yourapplication.py
/static
/style.css
/templates
layout.html
index.html
login.html
You can also change the location of the static files by setting the "static_folder" attribute on the app object. Check the docs here for setting the static_folder

Categories