Unable to add a task to todo list - python

When I try to add a new task on my website I get the message "POST /templates/todo" Error (404): "Not found" and cannot find what is wrong with the code. Can anyone help me figure it out? It was done on cs50ide software. If anyone could inform me whether I am able to create a functioning link for my website (I use python, flask, html and css) I would be very grateful! Thank you so much
add.html code:
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/css/styles.css" rel="stylesheet">
<title>
Add a New Task :)
</title>
</head>
<body>
<h1 class = "aligncenter">
<img class = "img1" src = "/static/images/logocarol.jpg" alt = "Logo" height = "200" width = "550"/>
</h1>
<h1 class="centergeneral fontsize">
Add any goals, dreams and aspirations you might have here:
</h1>
<form class="aligncenter" action="todo" method="POST">
<input id="task" name="task" type="text" placeholder="New Task :)">
<input id="submit" type="submit" disabled>
</form>
<script>
document.querySelector('#task').onkeyup = function(){
if (document.querySelector('#task').value === ''){
document.querySelector('#submit').disabled = true;
} else {
document.querySelector('#submit').disabled = false;
}
}
</script>
<form action="/">
<button type="submit" id = "back" class="btn btn-info margin"> BACK TO HOMEPAGE </button> <br> <br>
</form>
<form action="todo">
<button type="submit" id = "back" class="btn btn-outline-info margin"> BACK TO TO DO LIST </button> <br> <br>
</form>
</body>
todo.html code:
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/css/styles.css" rel="stylesheet">
<title>
To Do List! :)
</title>
</head>
<body>
<h1 class = "aligncenter">
<img class = "img1" src = "/static/images/logocarol.jpg" alt = "Logo" height = "200" width = "550"/>
</h1>
<h1 class="fonts centergeneral"> To Do List </h1>
<h2 class="fs-4 centergeneral"> What I Want to Achieve: </h2> <br>
<ul class="listcenter">
<script>
{%for todo in todos%}
<li> {{ todo }} <input type="checkbox" id="checkbox1"> </li>
{%endfor%}
</script>
</ul>
<a class="btn btn-outline-info margin" href = "add"> Add a New Task</a>
<a class="btn btn-outline-info" href = "clear"> Clear Tasks </a> <br>
<div class="backbuttons">
<form action="/">
<button type="submit" id = "back" class="btn btn-info"> BACK TO HOMEPAGE </button> <br> <br>
</form>
</div>
application.py code:
from flask import Flask, render_template, send_from_directory, request, redirect, session
from flask_session import Session
from cs50 import SQL
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/f1inschools')
def f1():
return render_template('f1inschools.html')
#app.route('/pdwt')
def pdwt():
return render_template('pdwt.html')
#app.route('/pros')
def pros():
return render_template('pros.html')
#app.route('/bookrecommendations')
def books():
return render_template('bookrecs.html')
#app.route('/todolist')
def todo():
if "todos" not in session:
session["todos"] = []
return render_template('todo.html', todos=session["todos"])
#app.route('/clear')
def clear():
return redirect("/todolist")
session["todos"] = []
#app.route('/add', methods=["GET", "POST"])
def add():
if request.method == "GET":
return render_template("add.html")
else:
todo = request.form.get("task")
session["todos"].append(todo)
return redirect("/todolist")

The function for adding tasks is at app.route("/add",methods=["GET","POST"]), but your form in the HTML has action="todo", so your form tries to send data to /todo which is nonexistent. To fix, simply change action="todo" to action="add".

Related

Call python's object method from flask jinja2 html file

I am trying to create youtube video downloader application using pytube and flask. All is done, except that a want to call pytube's stream download method from within the html script tag. How can i do it.
Here's my flask code
from flask import Flask, render_template, request
from pytube import YouTube
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html", data=None)
#app.route("/download", methods=["POST", "GET"])
def downloadVideo():
if request.method == "POST":
url = request.form["videourl"]
if url:
yt = YouTube(url)
title = yt.title
thumbnail = yt.thumbnail_url
streams = yt.streams.filter(file_extension='mp4')
data = [title, thumbnail, streams, yt]
return render_template("index.html", data=data)
if __name__ == "__main__":
app.run(debug=True)
and here's my html code
<!DOCTYPE html>
<html>
<head>
<title> Youtube Downloader </title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="stylesheet" href="static/css/style.css">
</head>
<body>
<div class="main">
<div class="header">
<div>
<img src="static/img/icon.png" width="48" height="48">
<h2> Youtube Downloader </h2>
</div>
<div>
<p> Convert and download youtube videos </p>
<p> in MP4 for free </p>
</div>
</div>
{% if not data %}
<div class="dform">
<form action="http://127.0.0.1:5000/download", method="POST">
<div class="inputfield">
<input type="input" name="videourl" placeholder="Search or Paste youtube link here" autocomplete="off">
<button type="submit"> Download </button>
</div>
</form>
</div>
{% else %}
<div class="videoinfo">
<img src="" class="thumbnail">
<h2> {{data[0]}} </h2>
</div>
<div class="quality">
<select id="streams">
{% for stream in data[2][:3] %}
<option value="{{stream.itag}}"> {{stream.resolution}} </option>
{% endfor %}
</select>
</div>
{% endif %}
</div>
<script type="text/javascript">
const image = document.querySelector(".thumbnail");
const select = document.querySelector("select");
let url = `{{data[1]}}`;
if (image) {
image.src = `${url}`;
window.addEventListener('change', function() {
var option = select.options[select.selectedIndex].value;
console.log(option);
{% set stream = data[3].get_by_itag(option) %}
{% stream.download() %}
});
}
</script>
</body>
</html>
I am trying to download the video using itag when a user clicks an option in the select element by using pytube get_by_itag() method.
From what I understand you want to do two things. You want to create a route on your flask app that will let serve up the youtube video based on an itag, and you want to be able to call that route from javascript.
This answer shows how to create a route to download the video.
To call a url that starts a file download from javascript you'll need to use the fetch method and open that link into an iFrame. This answer covers it.
Let me know if that covers your question.

I get "none" from the form when I execute the request.form.get("url") [duplicate]

This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 6 months ago.
I am using Flask in python with HTML.
I do not receive anything from the form, I do not know what I have wrong, I leave my code below.
I get "none" from the form when I execute the request.form.get("url")
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>YouTube Download</title>
<link rel="stylesheet" href="../static/css/style.css">
<link href="{{ url_for('static', filename='css/style.css') }}" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="banner">
<h1 class="title" data-text="Youtube Download"><i class="fa fa-music"></i> Youtube Download</h1>
<form action="{{ url_for('downloadMP3') }}" method="POST">
<p>Ingresa la URL del Video
</p>
<br>
<input class="form-control" type="text" id="url" name=“url” >
<div class="btn-group">
<button class="btn" type="submit" formaction="/downloadMP4">
<i class="fa fa-download"> </i> Download MP4
</button>
<button class="btn" type="submit" formaction="/downloadMP3">
<i class="fa fa-download"> </i> Download MP3
</button>
</div>
</form>
</div>
</body>
</html>
PYTHON FILE
from flask import Flask, render_template, request, Response, redirect, send_file
import os
from os import remove
import pafy
import moviepy.editor as mp
app = Flask(__name__)
path=os.getcwd() + '/'
#app.route('/')
def route():
return render_template('index.html')
#app.route('/downloadMP4', methods=['GET', 'POST'])
def downloadMP4():
if request.method == 'POST':
url = request.form.get("url")
video = pafy.new(url)
best = video.getbest(preftype="mp4")
best.download(path)
p = path + video.title + '.mp4'
return send_file(p, as_attachment=True)
#app.route('/downloadMP3', methods=['GET', 'POST'])
def downloadMP3():
if request.method == 'POST':
url = request.form.get("url")
video = pafy.new(url)
best = video.getbest(preftype="mp4")
best.download(path)
name = path + video.title + '.mp4'
clip = mp.VideoClip(name)
clip.audio.write_audiofile(path + video.title + '.mp3')
p = path + video.title + '.mp3'
return send_file(p, as_attachment=True)
if __name__ == '__main__':
app.run(host='localhost', port=5000)
I think the problem is in the HTML form but I don't know.
Any help is helpful, thanks.
To your input-field you have to add a name attribute
<input class="form-control" type="text" id="url" name="url">
should do the job. When sent to the flask-backend request.form.get() does not look for the id but the name attribute.
You got None because you didn't specify the name attribute in your url field, like this:
<input class="form-control" type="text" id="url" name="url">
request.form.get() looks at the value of name attribute and not the id

Flask: How can I send a text from python to a HTML textArea

I just started learning how to use flask in python and I'm doing a little practice to get information from my frontend , analyze it and then send the result back to the frontend in a TxtArea. I'm able to get the information from the first txtArea and analyze it, but I'm not sure of how to send the analysis output back to the frontend.
Basically I should be showing 'Hello world' in the right txtArea as a result of the input of the left txtArea.
Here is my code.
#app.route('/analisis',methods=["POST","GET"])
def analisis():
if request.method=="POST":
content=request.form["text1"]
result=analysis(content)
return redirect(url_for("analisis"))
else:
return render_template('analisis.html')```
And this is what I got for the html file:
<!DOCTYPE html>
<html>
<head>
<style>
textarea {
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<form action="#" method="post">
<h1>Input</h1>
<p><input type="submit" value="Analizar"/></p>
<textarea id="txt1" name="text1" rows="4" cols="50">
</textarea>
<textarea id="txt2" name="text2" rows="4" cols="50">
</textarea>
</form>
</body>
</html>
Any ideas?
You need to pass your data from the textarea, process it and return both values to the html
below is a sample route
#app.route('/sample', methods=["POST", "GET"])
def sample():
if request.method == 'POST':
sample_input = request.form.get('text1')
sample_output = sample_input + ' -> Processed'
return render_template('index.html', sample_input=sample_input, sample_output=sample_output)
elif request.method == 'GET':
return render_template('index.html')
sample html template
<!DOCTYPE html>
<html>
<head>
<style>
textarea {
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<form action="/sample" method="post">
<h1>Input</h1>
<p><input type="submit" value="Analizar"/></p>
<textarea id="txt1" name="text1" rows="4" cols="50">
{{ sample_input }}
</textarea>
<textarea id="txt2" name="text2" rows="4" cols="50">
{{ sample_output }}
</textarea>
</form>
</body>
</html>
When there is a POST requst, it will update the textarea with the appropriate values, when it is a GET request, it will give a blank textarea
content=request.form["text1"]
result=analysis(content) #I assume you have a function that analyzes this parameter
url_for('remove', variable=result)
and then in HTML
{{ variable }}

NameError: name '' is not defined using bottle in python

So I'm very new to all of this but I will try to tell you what question I have.
I'm trying to create a simpel wiki API using python, bottle and .txt since this is my assignment. I wrote my question further down, very thankful for quick help.
This is my .py:
from bottle import route, run, template, request, static_file, redirect
def read_articles_from_file():
articles = []
try:
my_file = open("wiki/articles.txt", "r").close()
content = my_file.read()
for article in content.slpit("/"):
if article != "":
articles.append(article)
return articles
except:
my_file = open("wiki/articles.txt", "w").close()
return articles
#route("/")
def index():
articles_from_file = read_articles_from_file()
return template("./static/index.html", articles = articles_from_file)
#route('/addera', method="POST")
#route('/addera', method="GET")
def save_article():
title = request.forms.get("title")
text = request.forms.get("text")
my_file = open("wiki/articles.txt", "a")
my_file.close()
redirect("/")
#route('/addera')
def show_save_article():
return template("./static/index.html")
#route('/<filename>.css')
def stylesheets(filename):
return static_file('{}.css'.format(filename), root='static')
if __name__ == '__main__':
run(host='localhost', port=8080, debug=True, reloader=True)
else:
print("Något gick fel")
This is my html for index:
<!doctype html>
<html lang="sv">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Wiki</title>
</head>
<body>
<div class="header">
<div class="container">
<h1 class="header-heading">Inlämning 5 Wiki</h1>
</div>
</div>
<div class="nav-bar">
<div class="container">
<ul class="nav">
<li>Visa alla artiklar</li>
<li>Lägg till artikel</li>
</ul>
</div>
</div>
<div class="content">
<div class="container">
<div class="main" id="artiklar">
<h2>Basic wiki</h2>
<hr>
<h3>Alla artiklar</h3>
<ul class="list-unstyled">
% for article in articles:
<li>{{ article }}</li>
% end
</ul>
<hr>
</div>
</div>
</div>
</div>
<div class="footer">
<div class="container">
© Copyright 2017
</div>
</body>
</html>
Question:
Why do I get this error?
screen dump
You have a route for index ("/") and addera ("/addera"). In your index route, you are passing the articles to the template. You are not passing the articles in the addera route which is causing a bad reference in the template.

Uploading video from phone to Google App Engine Blobstore

I'm using Python on Google App Engine as the backend for a Desktop/Mobile web app for video sharing. I'm having an issue uploading from an iPhone to the blobstore. Usually the page redirects after the upload URL is created, but this doesn't happen on the phone. Instead the browser navigates to the upload URL, but nothing is uploaded.
I can select a video to upload just fine, and if it's a long video, the phone will take awhile to navigate to the next page which seems to imply that something is being transferred, but nothing ends up in the blobstore.
Videos are uploaded with the following Python code.
class UploadPage(webapp2.RequestHandler):
def get(self):
upload_url = blobstore.create_upload_url('/uploadvideo')
template_values = {
'upload_url': upload_url,
}
template = JINJA_ENVIRONMENT.get_template('upload.html')
self.response.write(template.render(template_values))
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload = self.get_uploads()[0]
video = Videos(content=upload.key())
video.title = self.request.get('title')
video.description = self.request.get('description')
video.ratingDown = 0
video.ratingUp = 0
video.creator = users.get_current_user().nickname()
uniuqeIDFound = False
newID = random.randint(1000,9999)
while(uniuqeIDFound == False):
vids = db.GqlQuery("SELECT * "
"FROM Videos ")
uniuqeIDFound = True
for v in vids:
if (v.videoID == newID):
newID = random.randint(1,10000)
uniuqeIDFound = False
video.videoID = newID
db.put(video)
self.redirect('/home')
The upload page itself looks like this.
<!DOCTYPE html>
<html>
<head>
<title> Upload </title>
<meta charset="utf-8">
<link type="text/css" rel="stylesheet" href="/stylesheets/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />
</head>
<body>
<div class="fill">
<div class="container">
<ul class="nav nav-tabs">
<li>Home</li>
<li class="active">Upload Video</li>
<li>Logout</li>
<li>Contact Us</li>
</ul>
<h2 class="addColor">Tribal Knowledge</h2><h3 class="addColor">Upload a Video</h3>
<form class="form-horizontal" action="{{ upload_url }}" method="POST" enctype="multipart/form-data">
<textarea placeholder="Title..." name="title" cols="50" rows="1" autofocus="autofocus" required></textarea><br>
<textarea placeholder="Description..." name="description" cols="50" rows="4" autofocus="autofocus"></textarea><br>
Upload File: <input type="file" name="file"><br> <input class="btn btn-success" type="submit" name="submit" value="Upload Video">
</form>
</div>
</div>
</body>
</html>

Categories