HTML template doesn't display passed variables (Flask) - python

I pass the variable with render_template() and the html outputs empty space in place of the variable.
Here's my flask code based on a tutorial:
#import Flask
from flask import Flask, render_template, request
#create an instance of Flask
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
#app.route('/predict/', methods=['GET','POST'])
def predict():
if request.method == "POST":
#get form data
tv = request.form.get('tv')
radio = request.form.get('radio')
newspaper = request.form.get('newspaper')
return render_template('predict.html')
#call preprocessDataAndPredict and pass inputs
try:
prediction = preprocessDataAndPredict(tv, radio, newspaper) #pass prediction to template
return render_template('predict.html', my_prediction = prediction)
except ValueError:
return "Please Enter valid values"
pass
pass
def preprocessDataAndPredict(tv, radio, newspaper): #put all inputs in array
test_data = [tv, radio, newspaper]
print(test_data) #convert value data into numpy array
test_data = np.array(test_data).astype(np.float) #reshape array
test_data = test_data.reshape(1,-1)
print(test_data) #open file
file = open("lr_model.pkl","rb") #load trained model
trained_model = joblib.load(file) #predict
prediction = trained_model.predict(test_data)
return prediction
pass
if __name__ == '__main__':
app.run(debug=True)
And here is the predict.html file:
<!doctype html>
<html>
<head>
<title> Prediction </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head>
<body>
<div class="container">
<div class="row my-5 pl-3">
<p>Prediction is {{ my_prediction }}</p>
</div> </div>
</body>
</html>
I tried passing simple, hardcoded variables but the target html only displays "Prediction is" and doesn't show any passed variable.
I'll appreciate every suggestion on how to fix this!
Edit: also attaching the home.html file:
<!doctype html>
<html>
<head>
<title> Predict Sales </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head>
<body>
<div class="container">
<div class="row my-5 pl-3">
<h1>Predict Sales</h1>
</div> <!-- Starts form section -->
<div class="form-container ">
<form class="form-horizontal" action = "/predict/" method="post"> <div class="form-group row">
<label class="control-label col-sm-2" for="tv">TV:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="tv" name="tv">
</div>
</div> <div class="form-group row">
<label class="control-label col-sm-2" for="radio">Radio:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="radio" name="radio">
</div>
</div> <div class="form-group row">
<label class="control-label col-sm-2" for="newspaper">Newspaper:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="newspaper" name="newspaper">
</div>
</div> <div class="form-group row">
<label class="control-label col-sm-2" for=""> </label>
<div class="col-sm-offset-2 col-sm-4">
<button type="submit" class="btn btn-primary">Predict</button>
</div>
</div>
</form>
<!-- Ends form section -->
</div>
</div>
</body>
</html><!doctype html>
<html>
<head>
<title> Predict Sales </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head>
<body>
<div class="container">
<div class="row my-5 pl-3">
<h1>Predict Sales</h1>
</div> <!-- Starts form section -->
<div class="form-container ">
<form class="form-horizontal" action = "/predict/" method="post"> <div class="form-group row">
<label class="control-label col-sm-2" for="tv">TV:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="tv" name="tv">
</div>
</div> <div class="form-group row">
<label class="control-label col-sm-2" for="radio">Radio:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="radio" name="radio">
</div>
</div> <div class="form-group row">
<label class="control-label col-sm-2" for="newspaper">Newspaper:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="newspaper" name="newspaper">
</div>
</div> <div class="form-group row">
<label class="control-label col-sm-2" for=""> </label>
<div class="col-sm-offset-2 col-sm-4">
<button type="submit" class="btn btn-primary">Predict</button>
</div>
</div>
</form>
<!-- Ends form section -->
</div>
</div>
</body>
</html>

It seems that you always return
return render_template('predict.html')
When you POST something and you never reach the return with the value you have later.
Overall you need to handle what is happening when you do not have a POST request, in your case a GET that is which will render the initial html. And when something is submitted you should render or redirect the html with the values you want.
EDIT After some clarifications you gave
Please check below:
home.html
<!doctype html>
<html>
<head>
<title> Predict Sales </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head>
<body>
<div class="container">
<div class="row my-5 pl-3">
<h1>Predict Sales</h1>
</div> <!-- Starts form section -->
<div class="form-container ">
<form class="form-horizontal" action = "/predict/" method="post"> <div class="form-group row">
<label class="control-label col-sm-2" for="tv">TV:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="tv" name="tv">
</div>
</div> <div class="form-group row">
<label class="control-label col-sm-2" for="radio">Radio:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="radio" name="radio">
</div>
</div> <div class="form-group row">
<label class="control-label col-sm-2" for="newspaper">Newspaper:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="newspaper" name="newspaper">
</div>
</div> <div class="form-group row">
<label class="control-label col-sm-2" for=""> </label>
<div class="col-sm-offset-2 col-sm-4">
<button type="submit" class="btn btn-primary">Predict</button>
</div>
</div>
</form>
<!-- Ends form section -->
</div>
</div>
</body>
</html><!doctype html>
I removed the duplicate form to check only with one set of inputs.
predict.html is the same
flask code:
#import Flask
from flask import Flask, render_template, request
#create an instance of Flask
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
#app.route('/predict/', methods=['GET','POST'])
def predict():
if request.method == "POST":
#get form data
tv = request.form.get('tv')
radio = request.form.get('radio')
newspaper = request.form.get('newspaper')
prediction = preprocessDataAndPredict(tv, radio, newspaper)
return render_template('predict.html', my_prediction = prediction)
pass
def preprocessDataAndPredict(tv, radio, newspaper): #put all inputs in array
# test_data = [tv, radio, newspaper]
# print(test_data) #convert value data into numpy array
# test_data = np.array(test_data).astype(np.float) #reshape array
# test_data = test_data.reshape(1,-1)
# print(test_data) #open file
# file = open("lr_model.pkl","rb") #load trained model
# trained_model = joblib.load(file) #predict
# prediction = trained_model.predict(test_data)
prediction = "hello"
return prediction
if __name__ == '__main__':
app.run(debug=True)
I have added a call to your function before the rendering. I just return a string here just to demonstrate how you could set it up. I also commented the core functionality -i miss some libs- and make it to just return a value.
This works. So now when you click the button you will get:
Prediction is hello
in your browser. Can you build on this example?

Related

How can you create a registration form for an already existing template? Django

I'm looking to create a registration form but for a template that I've already build. The problem is that such template doesn't detect Django's prebuild form methods and the form isn't saved when the user enters his details. How can you fix this?
template:
{% load static %}
<!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, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>SB Admin 2 - Login</title>
<!-- Custom fonts for this template-->
<link href='{% static "vendor/fontawesome-free/css/all.min.css" %}' rel="stylesheet" type="text/css">
<link
href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
rel="stylesheet">
<!-- Custom styles for this template-->
<link href='{% static "css/sb-admin-2.min.css" %}' rel="stylesheet">
</head>
<body class="bg-gradient-primary">
<div class="container">
<div class="card o-hidden border-0 shadow-lg my-5">
<div class="card-body p-0">
<!-- Nested Row within Card Body -->
<div class="row">
<div class="col-lg-5 d-none d-lg-block bg-register-image"></div>
<div class="col-lg-7">
<div class="p-5">
<div class="text-center">
<h1 class="h4 text-gray-900 mb-4">Create an Account!</h1>
</div>
<form class="user" method="POST">
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
<input type="text" class="form-control form-control-user" id="exampleFirstName"
placeholder="First Name">
</div>
<div class="col-sm-6">
<input type="text" class="form-control form-control-user" id="exampleLastName"
placeholder="Last Name">
</div>
</div>
<div class="form-group">
<input type="email" class="form-control form-control-user" id="exampleInputEmail"
placeholder="Email Address">
</div>
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
<input type="password" class="form-control form-control-user"
id="exampleInputPassword" placeholder="Password">
</div>
<div class="col-sm-6">
<input type="password" class="form-control form-control-user"
id="exampleRepeatPassword" placeholder="Repeat Password">
</div>
</div>
<a href={% url 'register' %} class="btn btn-primary btn-user btn-block">
Register Account
</a>
<hr>
<a href="index.html" class="btn btn-google btn-user btn-block">
<i class="fab fa-google fa-fw"></i> Register with Google
</a>
<a href="index.html" class="btn btn-facebook btn-user btn-block">
<i class="fab fa-facebook-f fa-fw"></i> Register with Facebook
</a>
</form>
<hr>
<div class="text-center">
<a class="small" href="forgot-password.html">Forgot Password?</a>
</div>
<div class="text-center">
<a class="small" href="login.html">Already have an account? Login!</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src='{% static "vendor/jquery/jquery.min.js" %}'></script>
<script src='{% static "vendor/bootstrap/js/bootstrap.bundle.min.js" %}'></script>
<!-- Core plugin JavaScript-->
<script src='{% static "vendor/jquery-easing/jquery.easing.min.js" %}'></script>
<!-- Custom scripts for all pages-->
<script src='{% static "js/sb-admin-2.min.js"}'></script>
</body>
</html>
views.py(register function):
from django.shortcuts import render
from django.shortcuts import render
from .scraper import EmailCrawler
from django.http import HttpResponse
from celery import shared_task
from multiprocessing import Process
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from asgiref.sync import sync_to_async
from django.shortcuts import redirect
from .forms import CreateUserForm
def register(request):
if request.user.is_authenticated:
return redirect('login')
else:
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Account was created for' + user)
return redirect('login')
context = {'form':form}
return render(request, 'leadfinderapp/register.html', context)
forms.py:
from django.forms import ModelForm
from .models import Order
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
class OrderForm(ModelForm):
class Meta:
model = Order
fields = '__all__'
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
Any help would appreciate it. Thank you!

MultiValueDictKeyError: 'content'

i'm going to make the todo list using django...i did some code...but it throws an multiplevaluekeyerror
i tried c = request.POST.get('content', False)
but it gives always as False value
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import TodoItem
# Create your views here.
def home(request):
return render(request, 'home.html')
def work(request):
all_todo_items = TodoItem.objects.all()
return render(request, 'work.html', {'all_items': all_todo_items})
def addTodo(request):
c = request.POST['content']
new_item = TodoItem(content = c)
new_item.save()
return HttpResponseRedirect('/work/')
def deleteTodo(request, todo_id):
item_to_delete = TodoItem.objects.get(id=todo_id)
item_to_delete.delete()
return HttpResponseRedirect('/work/')
work.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{% static 'css/work.css' %}">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
<link rel="icon" href="{% static 'images/list.png' %}" type="image/png">
<title>Tasks</title>
</head>
<body>
<div class="container justify-content-center wrap1">
<div class="text-center heading">
<p><u>write your everyday task here!!!<u></p>
</div>
</div>
<ul style="list-style: none; color: #1b0573; font-weight: bold;" class="text-center">
{% for todo_item in all_items %}
<li>
<div class="row">
<div class="col-sm-6">
{{ todo_item.content }}
</div>
<div class="col-sm-2">
{{ todo_item.date_created }}
</div>
<div class="col-sm-1">
<form action="/deleteTodo/{{ todo_item.id }}" method="post" style="display: inline;">
{% csrf_token %}
<div class="form-group">
<button class="btn btn-outline-danger"><i class="fas fa-trash"></i></button>
</div>
</form>
</div>
</li>
{% endfor %}
</ul>
<div class="container">
<div class="row">
<div class="col-sm-11">
<form action="/addTodo/" method="post">
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" placeholder="write your task" name="content">
</div>
</form>
</div>
<div class="col-sm-1">
<form action="/addTodo/" method="post">
{% csrf_token %}
<div class="form-group">
<button class="btn btn-outline-success"><i class="fas fa-plus"></i></button>
</div>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('work/', views.work, name = 'work'),
path('addTodo/', views.addTodo, name = 'work'),
path('deleteTodo/<int:todo_id>/', views.deleteTodo, name = 'work'),
]
i was expecting no errors...but it throws an multiplevaluekeyerror
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'content'
you need submit first <form> that you have in your code that include <input name="content"> so in view can using request.POST["conten"] to get value of` . try this:
<div class="container">
<div class="row">
<div class="col-sm-11">
<form action="/addTodo/" method="post">
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" placeholder="write your task" name="content">
<input type="submit" value="submit new task">
</div>
</form>
</div>
</div>
</div>

How do I reset my HTML form with Python Flask?

I'm building a very simple web app (using Python Flask) that will display some images to the user and get some response from the user.
Below is my code (ignoring the other parts of my code not related to this question):
#app.route('/gallery',methods=['GET','POST'])
def get_gallery():
image_names = os.listdir(r'C:\Users\xxxvn\images')
b=[str(i)+"|"+str(request.form.get(i)) for i in image_names]
print (b)
return render_template("gallery.html", image_names=image_names)
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Gallery</h1>
</div>
{{image_names}}
<hr>
<form method="POST">
{% for image_name in image_names %}
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<img class="img-responsive" src=" {{url_for('send_image', filename=image_name)}}">
<input type="radio" name={{image_name}} id="radio1" value="YES" />YES<br>
<input type="radio" name={{image_name}} id="radio2" value="NO"/>NO<br>
<hr>
</div>
{% endfor %}
<input type="submit" name="submit_button" value="SUBMIT"/>
</form>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
crossorigin="anonymous"></script>
</body>
</html>
My current app
Question:
I want to reset the form as soon as the user hits submit and capture the output in list "B". The form should not be resubmitted with old values if the user hits refresh.
Do a request method check and put in your capture login in it.
from flask import request
#app.route('/gallery',methods=['GET','POST'])
def get_gallery():
image_names = os.listdir(r'C:\Users\xxxvn\images')
if request.method == "POST":
b=[str(i)+"|"+str(request.form.get(i)) for i in image_names]
print (b)
return render_template("gallery.html", image_names=image_names)

Bad Request The browser (or proxy) sent a request that this server could not understand

I have tried filling the add.html and when I click send I get the error above.
Bad Request
The browser (or proxy) sent a request that this server could not understand.
My app.py is as below.
from flask import Flask, render_template, url_for, redirect, request
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import requests
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://user:mypassword#localhost/mydb'
db=SQLAlchemy(app)
# class User(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# username = db.Column(db.String(80), unique=True, nullable=False)
# email = db.Column(db.String(120), unique=True, nullable=False)
# def __init__(self , username, email):
# self.username = username
# self.email = email
# def __repr__(self):
# return '<User %r>' % self.username
class Blogpost(db.Model):
id=db.Column(db.Integer, primary_key=True)
title=db.Column(db.String(50))
subtitle=db.Column(db.String(50))
author=db.Column(db.String(50))
date=db.Column(db.DateTime)
content=db.Column(db.Text)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/about')
def about():
return render_template('about.html')
#app.route('/post')
def post():
return render_template('post.html')
#app.route('/contact')
def contact():
return render_template('contact.html')
#app.route('/add')
def add():
return render_template('add.html')
#app.route('/addpost', methods=['POST'])
def addpost():
if request.method=='POST':
title = request.form['title']
subtitle = request.form['subtitle']
author = request.form['author']
date = request.form['date']
content = request.form['content']
post=Blogpost(title=title, subtitle=subtitle, author=author, date_posted=datetime.now(), content=content)
db.session.add(post)
db.session.commit()
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
#And below is my is my add.html file
<!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='bootstrap.min.css')}}" rel="stylesheet">
<!-- Custom fonts for this template -->
<link href="{{url_for('static', filename='font-awesome.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='clean-blog.min.css')}}" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav">
<div class="container">
<a class="navbar-brand" href="{{('/')}}">Start Bootstrap</a>
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
Menu
<i class="fa fa-bars"></i>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="{{('/')}}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{('/about')}}">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{('/post')}}">Sample Post</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{('/contact')}}">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Header -->
<header class="masthead" style="background-image: url('{{url_for('static', filename='contact-bg.jpg')}}')">
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="page-heading">
<h1>Create a new blogpost</h1>
<span class="subheading">You can create a new blogpost here</span>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<form name="addForm" id="addForm" name="addForm" method="POST" action="{{url_for('addpost')}}" novalidate>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Title</label>
<input type="text" class="form-control" placeholder="title" id="title" name="title" required data-validation-required-message="Please enter a title.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Sub-title</label>
<input type="email" class="form-control" placeholder="subtitle" name="subtitle" id="subtitle" required data-validation-required-message="Please enter your Sub-title.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Author</label>
<input type="tel" class="form-control" placeholder="author" name="author" id="author" required data-validation-required-message="Your Name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Post</label>
<textarea rows="5" class="form-control" placeholder="content" name="content" id="name" required data-validation-required-message="Please enter content."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div id="success"></div>
<div class="form-group">
<button type="submit" class="btn btn-primary" id="sendMessageButton">Send</button>
</div>
</form>
</div>
</div>
</div>
<hr>
<!-- Footer -->
<footer>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<ul class="list-inline text-center">
</ul>
<p class="copyright text-muted">Copyright © Your Website 2017</p>
</div>
</div>
</div>
</footer>
<!-- Bootstrap core JavaScript -->
<script src="{{url_for('static', filename='jquery.min.js')}}"></script>
<script src="{{url_for('static', filename='bootstrap.bundle.min.js')}}"></script>
<!-- Contact Form JavaScript -->
<script src="{{url_for('static', filename='jqBootstrapValidation.js')}}"></script>
<script src="{{url_for('static', filename='contact_me.js')}}"></script>
<!-- Custom scripts for this template -->
<script src="{{url_for('static', filename='clean-blog.min.js')}}"></script>
</body>
</html>
When I try submitting after filling the form I get the error:
Bad Request
The browser (or proxy) sent a request that this server could not understand.
I have tried outputting it on a file but I still get the error
I debugged this with adding
import pdb; pdb.set_trace()
to addpost() immediately after the request method check. It turns out that date = request.form['date'] instruction fails because there is no date on your form:
(Pdb) request
<Request 'http://localhost:5000/addpost' [POST]>
(Pdb) request.form
ImmutableMultiDict([('content', u'asdfasdfasdfasdf'), ('title', u'asdfasdf'), ('subtitle', u'adsfasdfasdf'), ('author', u'asdfasdfasdf')])
(Pdb) request.form['title']
u'asdfasdf'
(Pdb) request.form['date']
*** BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
Once I remove the date = request.form['date'], the error disappears.

Submit button is not working after using Bootstrap in Bottle template

I am using bottle framework and python to make a website. After using bootstrap, the submit button of my form is not working.
Here is my code in the button3.tpl file:
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>Insert Artist</h1>
</div>
<hr>
<div class="container"
<form role="form" method="post" action="/result4">
<div class="form-group">
<laber>National ID</label>
<input class="form-control" type="text" name="ID" value=""><br>
</div>
<div class="form-group">
<laber>Name</label>
<input class="form-control" type="text" name="Name" value=""><br>
</div>
<div class="form-group">
<laber>Surname</label>
<input class="form-control" type="text" name="Surname" value=""><br>
<div class="form-group">
<label>Birth Year</label>
<input class="form-control" type="number" name="Birth" min="1900" max="2016"><br>
</div>
<input class="form-control" type="submit" value="Update Information">
</form>
</div>
<hr>
</body>
Why does it not redirect in the proper link ?

Categories