'Flask CSS Error after pressing submit button
I have a flask web that makes prediction and returns it. The index page is rendered, the model receives data and makes a prediction and shows it correctly. But the issue is when flask tries to render the index.hmtl page again with the predicted data post because it looses the style (maybe css).
Flask app.py
from flask import Flask, render_template, request,flash
import pickle
import pandas as pd
import numpy as np
import os
# Variables Globales
MODEL_PATH = "models/xgb_v1_deploy.pkl"
#Carga del modelo
model = pickle.load(open(MODEL_PATH, "rb"))
#Inicializamos aplicación flask
app = Flask(__name__)
#Configuraciones para entrada de datos al modelo
categoric_vars = ['Sex', 'AgeCategory', 'Race', 'Diabetic', 'GenHealth']
target_var = ['HeartDisease']
numeric_vars = ['MentalHealth', 'BMI', 'PhysicalHealth', 'SleepTime']
yes_no_vars = ["Smoking","AlcoholDrinking","Stroke","DiffWalking","PhysicalActivity","Asthma","KidneyDisease","SkinCancer"]
features_col = numeric_vars+yes_no_vars+categoric_vars
@app.route('/',methods=['GET'])
def new():
return render_template('index.html')
@app.route('/predict', methods=['POST'] )
def predict():
if request.method == 'POST':
#Leemos Los campos de HTML cuando se ejecute la acción ----> action="{{url_for('predict')}}
data1=float(request.form['a']) # estado Mental MentalHealth
data2=float(request.form['b']) # BMI
data3=float(request.form['c']) # PhysicalHealth
data4=float(request.form['d']) # SleepTime
data5=float(request.form['e']) # Smoking
data6=float(request.form['f']) # AlcoholDrinking
data7=float(request.form['g']) # Stroke
data8=float(request.form['h']) # DiffWalking
data9=float(request.form['i']) # PhysicalActivity
data10=float(request.form['j']) # Asthma
data11=float(request.form['k']) # KidneyDisease
data12=float(request.form['l']) # SkinCancer
data13=float(request.form['m']) # Sexo
data14=float(request.form['n']) # Age
data15=float(request.form['o']) # Race
data16=float(request.form['p']) # Diabetic
data17=float(request.form['q']) # GenHEalth
features=np.array([data1,data2,data3,data4,data5,data6,data7,data8,data9,data10,data11,data12,data13,data14,data15,data16,data17])
df = pd.DataFrame([features] , columns=features_col)
print(features)
pred = model.predict(df)
print(pred)
def statement():
#Escribimos un mensaje para la predicción
if pred == 0:
return 'Resultado:- El modelo estima que con una probabilidad elevada no sufriras ninguna enfermedad cardíaca.'
elif pred == 1:
return 'Resultado:- Según el modelo existe una probabilidad elevada de que sufras una enfermedad de corazón a lo largo de tu vida. Consulta con tu médico'
return render_template('index.html', statement=statement())
else:
return render_template('index.html')
#Lanzamos el principal de la app
if __name__=='__main__':
app.run(debug=True)
HTML Code
<!DOCTYPE html>
<html lang="es">
<head>
<!-- Required meta tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{{url_for('static', filename='style.css')}}">
<!-- <link rel="stylesheet" type="text/css" href="\static\styles\style.css"> -->
<title>XGboost Predictor</title>
</head>
<header class="header">
<h1 class="logo"><a href="#">Kiril.M.</a></h1>
<ul class="main-nav">
<li><a href="#">Inicio</a></li>
<li><a href="https://www.linkedin.com/in/kiril-morozov-data/">LinkedIn</a></li>
<li><a href="https://github.com/kirilmn13">GitHub</a></li>
</ul>
</header>
<body>
<h1 style="text-align:center;color: rgb(236, 232, 232);font-family: inherit;padding-top: 50px;">Modelo XGBoost para estimar probabilidad de tener una enfermedad Cardíaca</h1>
<hr style="color: rgb(0, 0, 0);">
<h2 style="color: rgb(255, 255, 255);">Guía de uso</h2>
<div class="a">
<ul class="reglas">
<li>Estado Mental: Nº de días del último mes en los que consideras que no has tenido estres, depresión, malestar.</li>
<li>Índice de masa corporal: Bajo peso (IMC < 18,5), Rango normal (IMC = 18,5-24,9), Sobrepeso (IMC = 24.9-29,9), Obesidad (IMC >30) </li>
<li>Estado Físico: Nº de días del último mes en los que consideras que te has encontrado bien físicamente sin dolores, molestias, cansancio </li>
</ul>
</div>
<div class="login">
<form style="margin-top: 50px;padding-left:0px;" action="{{url_for('predict')}}" method="post">
<input type="text" placeholder="Estado Mental" aria-label="default input example" required='required' name="a">
<br><br>
<input type="text" placeholder="Índice de masa corpotal" aria-label="default input example" required='required' name="b">
<br><br>
<input type="text" placeholder="Estado Físico" aria-label="default input example" required='required' name="c">
<br><br>
<input type="text" placeholder="Horas de sueño diarias" aria-label="default input example" required='required' name="d">
<br><br>
<select aria-label="Fumador@" type="text" required='required' name="e">
<option value="1">Fumador@</option>
<option value="2">No Fumador@</option>
</select>
<br><br>
<select aria-label="Bebedor@" type="text" required='required' name="f">
<option value="1">Bebedor@</option>
<option value="2">No bebedor@</option>
</select>
<br><br>
<select aria-label="Infarto@" type="text" required='required' name="g">
<option value="1">He sufrido Infarto</option>
<option value="2">No he sufrido Infarto</option>
</select>
<br><br>
<select aria-label="Dificultad@" type="text" required='required' name="h">
<option value="1">Tengo dificultad para subir escaleras</option>
<option value="2">No tengo dificultad para subir escaleras</option>
</select>
<br><br>
<select aria-label="Actividad" type="text" required='required' name="i">
<option value="1">Hago Actividad Física</option>
<option value="2">No Hago actividad Física</option>
</select>
<br><br>
<select aria-label="Asma" type="text" required='required' name="j">
<option value="1">Tengo asma</option>
<option value="2">No tengo asma</option>
</select>
<br><br>
<select aria-label="childdisease" type="text" required='required' name="k">
<option value="1">He tenido enfermedad en la infancia</option>
<option value="2">No he tenido enfermedad en la infancia</option>
</select>
<br><br>
<select aria-label="cancer" type="text" required='required' name="l">
<option value="1">He tenido cancer de piel</option>
<option value="2">No he tenido cancer de piel</option>
</select>
<br><br>
<select aria-label="sexo" type="text" required='required' name="m">
<option value="1">Hombre</option>
<option value="2">Mujer</option>
</select>
<br><br>
<select aria-label="Edad" type="text" required='required' name="n">
<option value="1">Edad 18-24</option>
<option value="2">Edad 25-29</option>
<option value="3">Edad 30-34</option>
<option value="4">Edad 35-39</option>
<option value="5">Edad 40-44</option>
<option value="6">Edad 45-49</option>
<option value="7">Edad 50-54</option>
<option value="8">Edad 55-59</option>
<option value="9">Edad 60-64</option>
<option value="10">Edad 65-69</option>
<option value="11">Edad 70-74</option>
<option value="12">Edad 75-79</option>
<option value="12">Edad 80 o más</option>
</select>
<br><br>
<select aria-label="Raza" type="text" required='required' name="o">
<option value="1">Blanco</option>
<option value="2">De color</option>
<option value="3">Asiático</option>
<option value="4">Indio-Americano</option>
<option value="5">Hispano</option>
<option value="6">Otro</option>
</select>
<br><br>
<select aria-label="Diabetes" type="text" required='required' name="p">
<option value="1">Diabético</option>
<option value="2">No diabético</option>
<option value="3">Diabetes en el embarazo</option>
<option value="4">Casi diabético</option>
</select>
<br><br>
<select aria-label="Salud" type="text" required='required' name="q">
<option value="1">Salud general : Excelente</option>
<option value="2">Salud general : Muy buena</option>
<option value="3">Salud general : Regular</option>
<option value="4">Salud general : Mejorable</option>
<option value="4">Salud general : Pésima</option>
</select>
<br><br>
<button style="margin-left:00px" type="submit" class="btn btn-outline-danger btn-lg">Predict</button><br><br>
<!-- <b style="color: rgb(255, 255, 255);font-size: 22px;">{{statement}}</b> -->
</form>
<div>
<!-- Our 'result' is false until a prediction has been made -->
{% if statement %}
<br>
<!-- Print prediction -->
<br> Predicted number of bikes in use:
<p style="font-size:50px">{{ statement }}</p>
{% endif %}
</div>
</div>
<div class="github">
<p><a href="https://github.com/kirilmn13">GitHub con código abierto</a></p>
</div>
<br>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0"
crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script>
-->
</body>
</html>
Any idea?
Thank you
Solution 1:[1]
It looks like you are using bootstrap for your css styling, etc. You will have to install flask-bootstrap to help make it work. As a result, I believe that may be the issue you are having with it losing it's styling.
Installation - Here is how you would go about installing it.
However here is the basic run down from the website:
You install it like any other module for python:
pip install flask-bootstrap
After you install it you import it as follows:
from flask import Flask
from flask_bootstrap import Bootstrap
def create_app():
app = Flask(__name__)
Bootstrap(app)
return app
The link is above, and it should walk you through it. However, if you get confused on this I would recommend just transferring it to vanilla css and having it that way.
If you are losing your style it is more than likely either the mixture of flask and bootstrap / utility styling classes. I did not see anything wrong with your HTML that would go about removing styles.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | thomas lee ray |