Python - my web application keep displaying "Hello World!" - python

So, I'm facing an issue here. I have installed Flask and tried to run the code sample in order to test:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
So far so good. However, after changing a bit the code within my python web app, when I run it on localhost, the browser opens the previous page with Hello World!. What am I doing wrong here?
Here's my final code in Python:
from flask import Flask, render_template, redirect, url_for, request
from student import Student
students = []
app = Flask(__name__)
#app.route("/", methods=["GET", "POST"])
def students_page():
if request.method == "POST":
new_student_id = request.form.get("student-id", "")
new_student_name = request.form.get("name", "")
new_student_last_name = request.form.get("last-name", "")
new_student = Student(name=new_student_name, student_id=new_student_id)
students.append(new_student)
return redirect(url_for("students_page"))
return render_template("index.html", students=students)
if __name__ == "__main__":
app.run(debug=True)
HTML file code:
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<title>A title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<style>
body {
padding-top: 70px;
}
footer {
margin-top: 50px;
padding-top: 20px;
padding-bottom: 10px;
background-color: #f5f5f5;
}
.text-muted {
color: #777;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">App</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>Students</li>
<li>About</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h1>A H1</h1>
<p>A paragraph</p>
</div>
<div class="page-header">
<h1>All Students</h1>
</div>
<div class="row">
<div class="col-md-12">
<table class="table table-striped">
<thead>
<tr>
<th>Student ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for student in students %}
<tr>
<td>{{ student.student_id }}</td>
<td>{{ student.name }}</td>
<td>{{ student.last_name }}</td>
<td>
<button class="btn btn-primary btn-sm">Edit</button>
<button class="btn btn-danger btn-sm">Delete</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="page-header">
<h1>Add a Student</h1>
</div>
<div class="row">
<div class="col-md-8">
<form method="POST">
<div class="form-group">
<label for="student-id">Student ID</label>
<input type="number" class="form-control" id="student-id" placeholder="Student ID" name="student-id">
</div>
<div class="form-group">
<label for="first-name">First Name</label>
<input type="text" class="form-control" id="first-name" placeholder="First Name" name="name">
</div>
<div class="form-group">
<label for="last-name">Last Name</label>
<input type="text" class="form-control" id="last-name" placeholder="Last Name" name="last-name">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
<footer class="footer">
<div class="container">
<p class="text-muted">footer</p>
</div>
</footer>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
</body>
</html>

I think you need to "Empty Cache and Hard Reload". Try as below:
Hold F12 and right click on the refresh icon (circular icon on the top left) and select 'Empty Cache and Hard Reload'.
You can find details from here

Well, apparently I was able to overpass this by force stopping my web app to run under localhost directly from PyCharm which initially I thought it's automatically stopping when I close my browser:
Hope will help!

Related

url_for in Flask always return error 304,even after clearing caches in chrome

<!DOCTYPE html>
<html style="font-size: 16px;">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<meta name="keywords" content="Login">
<meta name="description" content="">
<meta name="page_type" content="np-template-header-footer-from-plugin">
<title>Arcade</title>
<link rel="stylesheet" type='text/css' href="{{ url_for('static',filename='css/nicepage.css') }}" media="screen">
<link rel="stylesheet" type='text/css' href=" {{ url_for('static',filename='CSS/Arcade.css') }}" media="screen">
<script class="u-script" type="text/javascript" src="{{ url_for('static',filename='JS/jquery.js') }}" defer=""></script>
<script class="u-script" type="text/javascript" src="{{ url_for('static',filename='JS/nicepage.js') }}" defer=""></script>
<meta name="generator" content="Nicepage 4.10.5, nicepage.com">
<link id="u-theme-google-font" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,500,500i,700,700i,900,900i|Open+Sans:300,300i,400,400i,500,500i,600,600i,700,700i,800,800i">
<script type="application/ld+json">{
"#context": "http://schema.org",
"#type": "Organization",
"name": ""
}</script>
<meta name="theme-color" content="#478ac9">
<meta property="og:title" content="Arcade">
<meta property="og:type" content="website">
</head>
<body class="u-body u-xl-mode"><header class="u-clearfix u-header u-palette-1-light-1 u-header" id="sec-bc93"><div class="u-clearfix u-sheet u-sheet-1">
<nav class="u-menu u-menu-dropdown u-offcanvas u-menu-1">
<div class="menu-collapse" style="font-size: 1rem; letter-spacing: 0px;">
<a class="u-button-style u-custom-left-right-menu-spacing u-custom-padding-bottom u-custom-top-bottom-menu-spacing u-nav-link u-text-active-palette-1-base u-text-hover-palette-2-base" href="#">
<svg class="u-svg-link" viewBox="0 0 24 24"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#menu-hamburger"></use></svg>
<svg class="u-svg-content" version="1.1" id="menu-hamburger" viewBox="0 0 16 16" x="0px" y="0px" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><g><rect y="1" width="16" height="2"></rect><rect y="7" width="16" height="2"></rect><rect y="13" width="16" height="2"></rect>
</g></svg>
</a>
</div>
<div class="u-custom-menu u-nav-container">
<ul class="u-nav u-unstyled u-nav-1"><li class="u-nav-item"><a class="u-button-style u-nav-link u-text-active-palette-1-base u-text-hover-palette-2-base" style="padding: 10px 20px;">Home</a>
</li><li class="u-nav-item"><a class="u-button-style u-nav-link u-text-active-palette-1-base u-text-hover-palette-2-base" href="About.html" style="padding: 10px 20px;">About</a>
</li><li class="u-nav-item"><a class="u-button-style u-nav-link u-text-active-palette-1-base u-text-hover-palette-2-base" href="Contact.html" style="padding: 10px 20px;">Contact</a>
</li><li class="u-nav-item"><a class="u-button-style u-nav-link u-text-active-palette-1-base u-text-hover-palette-2-base" style="padding: 10px 20px;">Profile</a>
</li></ul>
</div>
<div class="u-custom-menu u-nav-container-collapse">
<div class="u-black u-container-style u-inner-container-layout u-opacity u-opacity-95 u-sidenav">
<div class="u-inner-container-layout u-sidenav-overflow">
<div class="u-menu-close"></div>
<ul class="u-align-center u-nav u-popupmenu-items u-unstyled u-nav-2"><li class="u-nav-item"><a class="u-button-style u-nav-link">Home</a>
</li><li class="u-nav-item"><a class="u-button-style u-nav-link" href="About.html">About</a>
</li><li class="u-nav-item"><a class="u-button-style u-nav-link" href="Contact.html">Contact</a>
</li><li class="u-nav-item"><a class="u-button-style u-nav-link">Profile</a>
</li></ul>
</div>
</div>
<div class="u-black u-menu-overlay u-opacity u-opacity-70"></div>
</div>
</nav>
</div></header>
<section class="u-clearfix u-section-1" id="sec-24f5">
<div class="u-clearfix u-expanded-width u-gutter-0 u-layout-wrap u-layout-wrap-1">
<div class="u-gutter-0 u-layout">
<div class="u-layout-row">
<div class="u-align-center u-container-style u-image u-layout-cell u-size-30 u-image-1" data-image-width="1200" data-image-height="900">
<div class="u-container-layout u-container-layout-1" src=""></div>
</div>
<div class="u-align-left u-container-style u-layout-cell u-size-30 u-white u-layout-cell-2">
<div class="u-container-layout u-container-layout-2">
<h2 class="u-text u-text-default u-text-1">Login</h2>
<div class="u-form u-form-1">
<form action="#" method="POST" class="u-clearfix u-form-spacing-10 u-form-vertical u-inner-form" source="custom" name="form" style="padding: 10px;">
<div class="u-form-group u-form-name">
<label for="name-e834" class="u-label">Username</label>
<input type="text" placeholder="Enter your Username" id="name-e834" name="name" class="u-border-1 u-border-grey-30 u-input u-input-rectangle u-white" required="">
</div>
<div class="u-form-email u-form-group">
<label for="email-e834" class="u-label">Password</label>
<input type="email" placeholder="Enter your Password" id="email-e834" name="email" class="u-border-1 u-border-grey-30 u-input u-input-rectangle u-white" required="">
</div>
<div class="u-align-center u-form-group u-form-submit">
Submit
<input type="submit" value="submit" class="u-form-control-hidden">
</div>
<div class="u-form-send-message u-form-send-success"> Thank you! Your message has been sent. </div>
<div class="u-form-send-error u-form-send-message"> Unable to send your message. Please fix errors then try again. </div>
<input type="hidden" value="" name="recaptchaResponse">
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<footer class="u-align-center u-clearfix u-footer u-grey-80 u-footer" id="sec-48a0"><div class="u-align-left u-clearfix u-sheet u-sheet-1"></div></footer>
<section class="u-backlink u-clearfix u-grey-80">
<a class="u-link" href="https://nicepage.com/website-templates" target="_blank">
<span>Website Templates</span>
</a>
<p class="u-text">
<span>created with</span>
</p>
<a class="u-link" href="" target="_blank">
<span>Website Builder Software</span>
</a>.
</section><span style="height: 64px; width: 64px; margin-left: 0px; margin-right: auto; margin-top: 0px; background-image: none; right: 20px; bottom: 20px; padding: 15px;" class="u-back-to-top u-black u-icon u-icon-circle u-opacity u-opacity-85" data-href="#">
<svg class="u-svg-link" preserveAspectRatio="xMidYMin slice" viewBox="0 0 551.13 551.13"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#svg-1d98"></use></svg>
<svg class="u-svg-content" enable-background="new 0 0 551.13 551.13" viewBox="0 0 551.13 551.13" xmlns="http://www.w3.org/2000/svg" id="svg-1d98"><path d="m275.565 189.451 223.897 223.897h51.668l-275.565-275.565-275.565 275.565h51.668z"></path></svg>
</span>
</body>
</html>
The above is my HTML code.I have used url_for for rendering the template with css.
from flask import Flask,render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
return render_template('Arcade.html')
if __name__ == '__main__':
app.debug = True
app.run()
app.run(debug = True)
The above is my python flask code. When i tried to run the code i got 304 erroe.So i cleared my browser cache and tried to rehost the application. But still the url_for couldn't grab the css and js files properly. No matter how many times i clear the cache and try I couldn't get the expected result.Please look into it and help me.
Note: I have properly created a static folder and saved the css and js files in a separate folders namely JS and CSS.
You are receiving this error because the cached version of the requested file is the same as the file to be sent.
Fix it by:
Clear the Chrome's Cache Data.
It is possible that a Computer Malware might be causing that problem, so run a Malware Scan.
As a precautionary step, I'd suggest you also disable any extensions you have installed on your browser.
Other Potential Problems
If it hasn't been solved by any of the methods above, it might be a DNS issue.
Go to DNS settings
Click clear host cache

Bootstrap sidebars rendered by Flask don't collapse

I am creating a Flask Web App and I want to use a Bootstrap 5.0 sidebar so I went to Bootstrap example page and downloaded the example that fits my needs. The plain HTML/CSS/JS file works fine. If you click on the buttom in the left of first level options the second level colapse/expand automatically. But when I call the same HTML file using render_template Flask function the colapse/expand don't work.
Here is the original HTML file (I removed a symbol svg session due to size limit here)
<!doctype html> <html lang="en"> <head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.84.0">
<title>Sidebars · Bootstrap v5.0</title>
<link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/sidebars/">
<!-- Bootstrap core CSS --> <link href="../assets/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
#media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
<!-- Custom styles for this template -->
<link href="sidebars.css" rel="stylesheet"> </head> <body>
<main> <h1 class="visually-hidden">Sidebars examples</h1>
<div class="flex-shrink-0 p-3 bg-white" style="width: 280px;">
<a href="/" class="d-flex align-items-center pb-3 mb-3 link-dark text-decoration-none border-bottom">
<svg class="bi me-2" width="30" height="24"><use xlink:href="#bootstrap"/></svg>
<span class="fs-5 fw-semibold">Collapsible</span>
</a>
<ul class="list-unstyled ps-0">
<li class="mb-1">
<button class="btn btn-toggle align-items-center rounded collapsed" data-bs-toggle="collapse" data-bs-target="#home-collapse" aria-expanded="false">
Home
</button>
<div class="collapse show" id="home-collapse">
<ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
<li>Overview</li>
<li>Updates</li>
<li>Reports</li>
</ul>
</div>
</li>
<li class="mb-1">
<button class="btn btn-toggle align-items-center rounded collapsed" data-bs-toggle="collapse" data-bs-target="#dashboard-collapse" aria-expanded="false">
Dashboard
</button>
<div class="collapse" id="dashboard-collapse">
<ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
<li>Overview</li>
<li>Weekly</li>
<li>Monthly</li>
<li>Annually</li>
</ul>
</div>
</li>
<li class="mb-1">
<button class="btn btn-toggle align-items-center rounded collapsed" data-bs-toggle="collapse" data-bs-target="#orders-collapse" aria-expanded="false">
Orders
</button>
<div class="collapse" id="orders-collapse">
<ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
<li>New</li>
<li>Processed</li>
<li>Shipped</li>
<li>Returned</li>
</ul>
</div>
</li>
<li class="border-top my-3"></li>
<li class="mb-1">
<button class="btn btn-toggle align-items-center rounded collapsed" data-bs-toggle="collapse" data-bs-target="#account-collapse" aria-expanded="false">
Account
</button>
<div class="collapse" id="account-collapse">
<ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
<li>New...</li>
<li>Profile</li>
<li>Settings</li>
<li>Sign out</li>
</ul>
</div>
</li>
</ul> </div>
<div class="b-example-divider"></div>
</main>
<script src="../assets/dist/js/bootstrap.bundle.min.js"></script>
<script src="sidebars.js"></script> </body> </html>
My application is supposed to run on a intranet so I download all the css and js file and save them in the static folder of my Flask app and changed the references in HTML file which became this way.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.84.0">
<title>Sidebars · Bootstrap v5.0</title>
<link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/sidebars/">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" type="text/css" href={{ url_for("static",filename="css/bootstrap.css" ) }}>
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
#media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
<!-- Custom styles for this template -->
<link rel="stylesheet" type="text/css" href={{ url_for("static",filename="css/sidebars.css" ) }}>
</head>
<body>
<main>
<h1 class="visually-hidden">Sidebars examples</h1>
<div class="flex-shrink-0 p-3 bg-white" style="width: 280px;">
<a href="/" class="d-flex align-items-center pb-3 mb-3 link-dark text-decoration-none border-bottom">
<svg class="bi me-2" width="30" height="24"><use xlink:href="#bootstrap"/></svg>
<span class="fs-5 fw-semibold">Collapsible</span>
</a>
<ul class="list-unstyled ps-0">
<li class="mb-1">
<button class="btn btn-toggle align-items-center rounded collapsed" data-bs-toggle="collapse" data-bs-target="#home-collapse" aria-expanded="false">
Home
</button>
<div class="collapse show" id="home-collapse">
<ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
<li>Overview</li>
<li>Updates</li>
<li>Reports</li>
</ul>
</div>
</li>
<li class="mb-1">
<button class="btn btn-toggle align-items-center rounded collapsed" data-bs-toggle="collapse" data-bs-target="#dashboard-collapse" aria-expanded="false">
Dashboard
</button>
<div class="collapse" id="dashboard-collapse">
<ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
<li>Overview</li>
<li>Weekly</li>
<li>Monthly</li>
<li>Annually</li>
</ul>
</div>
</li>
<li class="mb-1">
<button class="btn btn-toggle align-items-center rounded collapsed" data-bs-toggle="collapse" data-bs-target="#orders-collapse" aria-expanded="false">
Orders
</button>
<div class="collapse" id="orders-collapse">
<ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
<li>New</li>
<li>Processed</li>
<li>Shipped</li>
<li>Returned</li>
</ul>
</div>
</li>
<li class="border-top my-3"></li>
<li class="mb-1">
<button class="btn btn-toggle align-items-center rounded collapsed" data-bs-toggle="collapse" data-bs-target="#account-collapse" aria-expanded="false">
Account
</button>
<div class="collapse" id="account-collapse">
<ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
<li>New...</li>
<li>Profile</li>
<li>Settings</li>
<li>Sign out</li>
</ul>
</div>
</li>
</ul>
</div>
<div class="b-example-divider"></div>
</main>
<script src={{ url_for("static",filename="js/bootstrap.js" ) }}></script>
<script src={{ url_for("static",filename="js/bootstrap.bundle.js" ) }}></script>
<script src={{ url_for("static",filename="js/sidebar.js" ) }}></script>
</body>
</html>
and here is the python files I use to create the app.
the init.py in the main folder to create the Blueprint.
from flask import Blueprint
main = Blueprint('main',__name__)
from . import views
the init.py in the app folder
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_googlecharts import GoogleCharts
bootstrap = Bootstrap()
moment = Moment()
def create_app():
app = Flask(__name__)
app.debug=True
with app.app_context():
bootstrap.init_app(app)
moment.init_app(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app
and the view.py file
from flask import Flask,session,request,render_template,jsonify,url_for,redirect,flash
from flask_bootstrap import Bootstrap
from . import main
#main.route("/")
def home():
return render_template('index.html')
I didn't changed anything in the css/js from boostrap. Does anyone have ever seen something like that?
Man. It is just because I spent 15 minutes writing a question and 5 minutes after I posted it I found the problem. The problem was these line in the second html file.
<script src={{ url_for("static",filename="js/bootstrap.js" ) }}></script>
I don't know why but this is unecessary and was causing some error on the page animation.

Python Flask / Sqlite: How to embed images in a post content

I am new in programming and in Python Flask and I am trying to design a blog as first project. I was able to create a page ("Add") directly connected to my SQLite database in order to write and publish the post directly there. The problem is that I have not thought that I would also like to add images within the text content and I have no idea how to do it. This is my main page:
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/admin/Desktop/Blog_Project/blog2.db'
db = SQLAlchemy(app)
class Blogpost2(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(20))
date_posted = db.Column(db.DateTime)
content = db.Column(db.Text)
db.create_all()
#app.route('/')
def index():
posts = Blogpost.query.all()
return render_template('index.html', posts = posts)
#app.route('/about')
def about():
return render_template('about.html')
##app.route('/post')
#def post():
#return render_template('post.html')
#app.route('/post/<int:post_id>')
def post(post_id):
post = Blogpost2.query.filter_by(id=post_id).one()
date_posted = post.date_posted.strftime('%d %B, %Y')
return render_template('post.html', post=post, date_posted = date_posted)
#app.route('/contact')
def contact():
return render_template('contact.html')
#app.route('/prova')
def prova():
return render_template('prova.html')
#app.route('/add')
def add():
return render_template('add.html')
#app.route('/addpost', methods=['POST'])
def addpost():
title = request.form['title']
subtitle = request.form['subtitle']
author = request.form["author"]
content = request.form['content']
#return '<h1>Title:{} Subtitle:{} Author:{} Content:{} <h1/>'.format(title, subtitle, author, content)
post = Blogpost2(title=title, subtitle=subtitle, author=author, content=content, date_posted = datetime.now())
db.session.add(post)
db.session.commit()
return redirect(url_for('index'))
if __name__ == "__main__":
app.run(debug = True)
As you can see, the blog title, subtitle, author, content, and so on would be entered in the SQLlite database. That would happen trough the "Add" page, of which here you can see the code:
<!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="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> -->
<link href= "{{ url_for('static', filename='bootstrap.min.css')}}" rel="stylesheet">
<!-- Custom fonts for this template -->
<!-- <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> -->
<link href="{{url_for('static', filename = 'fontawesome.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= "{{ url_for('index') }}">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="fas 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="{{ url_for('index')}}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('about')}}">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('contact')}}">Contact</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('prova')}}">Prova</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Header -->
<header class="masthead" style="background-image: url('img/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>Aggiungi un post </h1>
<span class="subheading"> </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" 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" name = "title" id="title" required data-validation-required-message="Dai un titolo al tuo post">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Subtitle</label>
<input type="text" class="form-control" placeholder="Subtitle" name = "subtitle" id="subtitle" required data-validation-required-message="Please enter your email address.">
<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="text" class="form-control" placeholder="Author" name = "author" id="author" required data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Blog Content</label>
<textarea rows="5" class="form-control" placeholder="Blog content" name = "content" id="content" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div id="success"></div>
<button type="submit" class="btn btn-primary" id="sendMessageButton">Send</button>
</form>
</div>
</div>
</div>
<hr>
<!-- Footer -->
<footer>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<!-- Qua inizia la parte inferiore-->
<p class="copyright text-muted">Copyright © Your Website 2020</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.min.js')}}"></script>
<!-- Custom scripts for this template -->
<script src="{{ url_for('static', filename = 'clean-blog.min.js')}}"> </script>>
</body>
</html>
But is there a way to embed images within the post content? Or maybe should I choose another way to display text and images together?
Thank you very much in advance, every suggestion would be really appreciated!
Firstly, you need a way to upload an image. You can do this in several ways; Stack Overflow uses links to hosted images which are rendered with the src attribute of the img tag. Or you could get your user to upload an image.
Once you've validated the image chosen (if it's being uploaded), you should add it to your flask static folder, or from wherever you serve static files, and add a field that looks something like this to your db.Model:
image_path = db.Column(db.String(128)) # swap 128 for something suitable to your path length
Then, you can use the HTML img tag and its attribute src to get the image from your server like this:
<h1>{{ blog.author.name }} says: </h1>
<h2>{{ blog.title }}</h2>
<p>
{{ blog.content }}
</p>
<img src="{{ blog.image_path }}">

Python Django Webapp is not responsive in smartphone

I have developed my first web app in python Django framework, deployed in pythonanywhere.com web server.
I have already used the latest bootstrap in this app, but it is not responsive properly on a smartphone screen. responsive in laptop and tablet but not in a smartphone.
You can also check it in your phone "http://sandeepbhatt.pythonanywhere.com/".
please look into my base.html and index.html code, where is the problem, also please let me know if there are any details required to figure out this problem which is not mention in this post.
My base.html code:
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<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.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<title>PIV</title>
<!-- <link rel="stylesheet" href="{% static "css/index.css" %}"> -->
</head>
<body>
<!-- <style>
body{ background: url("{% static "images/background.jpg" %}"); background-size: cover; background-repeat: no-repeat;}
</style> -->
<!-- Navbar start from here -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<!-- <a class="navbar-brand" href="">Navbar</a> -->
<!-- Just an image -->
<nav class="navbar navbar-light bg-light">
<a class="navbar-brand" href="{% url 'index' %}">
<img src="{% static " images/logo.jpg" %}" width="70" height="50" alt="">
</a>
</nav>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="{% url 'logout' %}">Logout</a>
</li>
{% else %}
<!-- <li class="nav-item">
<a class="nav-link" href="{% url 'survey_app:user_login'%}">Login</a>
</li> -->
{% endif %}
<li class="nav-item">
<a class="nav-link" href="{% url 'survey_app:analysis' %}">Analysis</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'survey_app:tracking' %}">Tracking</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'admin:index' %}">Admin</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'survey_app:register' %}">Register</a>
</li>
</ul>
</div>
</nav>
</body>
<div class="container">
{% block contant %}
{% endblock %}
</div>
<!-- footer -->
<div class="card text-center">
<div class="card-footer text-muted">
Powered By <small>Political India Venture</small>
©2019
</div>
</div>
</html>
My index.html code:
<!DOCTYPE html>
{% extends 'survey_app/base.html' %}
{% load static %}
{% block contant %}
<head>
<link rel="stylesheet" href="{% static " css/login_form.css" %}">
<!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> -->
</head>
<!-- <style>
body{ background: url("{% static "images/background.jpg" %}"); background-size: cover; background-repeat: no-repeat;}
</style> -->
<div class="row">
<div class="col">
<h2>Welcome to Political India Venture </h2>
<h2>Survey App!</h2>
<h5 class="font-italic<div class=" row">
<h5>Get the answers you need</h5>
<div class="wrapper">
<form method="POST" class="form-signin" action="{% url " survey_app:user_login" %}">
{% csrf_token %}
{# A more "HTML" way of creating the login form#}
<h2 class="form-signin-heading">Please login</h2>
<input type="text" class="form-control" name="username" placeholder="User Name" required="" autofocus="" />
<input type="password" class="form-control" name="password" placeholder="Password" required="" />
<label class="checkbox">
<input type="checkbox" value="remember-me" id="rememberMe" name="rememberMe"> Remember me
</label>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
</form>
</div>
</div>
</div>
{% endblock %}
I found the solution after number of testing in my app and found there was only one bootstrap tag missing.
I just add this in my base.html file:
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
and now it is proper responsive on every device.
Your template is broken, look at <h5> class-"font-italic there is no closure (in index.html)

Python mechanicalsoup get web form

I am writing a standalone bot that log into JitJat, an anonymous instant messaging site and send a message to a user. I successfully do this and I reach the index where I select my recipient.
Finally, I can chat with somebody at the chat but whenever I try to get the form of the page I get None.
I tried to do this many times, using robobrowser, requests and mechanicalsoup.
Here my script:
import mechanicalsoup
#Current url: https://jitjat.org/login.php
browser = mechanicalsoup.StatefulBrowser()
browser.open('https://jitjat.org/login.php')
print('Current url: ' + str(browser.get_url()))
browser.select_form()
browser['username'] = 'my username'
browser['password'] = 'my password'
browser.submit_selected()
print('Redirect: ' + str(browser.get_url()))
#Current url: https://jitjat.org/index.php
browser.follow_link("recipient username")
print('Redirect: ' + str(browser.get_url()))
#Current url: https://jitjat.org/chat.php?id=(recipient username)
browser.select_form()
print(browser.get_current_form().print_summary())
Here the page source:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JitJat - anonymous instant messaging</title>
<link href="css/jChat.css" rel="stylesheet" media="screen" type="text/css" />
<link href="css/reset.css" rel="stylesheet" media="screen" type="text/css" />
<link href="css/bootstrap.css" rel="stylesheet" media="screen" type="text/css" />
<link href="css/bootstrap-responsive.css" rel="stylesheet" media="screen" type="text/css" />
<link href="css/user_css.css" rel="stylesheet" media="screen" type="text/css" />
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/bootstrap.js" type="text/javascript"></script>
<script src="js/jChat.js" type="text/javascript"></script>
<script src="js/jquery.nicescroll.js" type="text/javascript"></script>
<script src="js/custom.js" type="text/javascript"></script>
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<div id="header">
<div id="logo">
<h1>logo</h1>
</div>
<div id="info">
<ul id="userBox">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">ni47gv2x9ne<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><span class="icon-off"></span> <strong>Logout</strong></li>
</ul>
</li>
</ul>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<div class="container">
<ul class="breadcrumb">
<li>Home<span class="divider">»</span></li>
<li class="active">Chat</li>
</ul>
</div>
<div class="container">
<ul class="breadcrumb" align="center">
<li><noscript>
<span style="font-weight: normal; color: #ff0000">You need to have scripting enabled to use Chat.</span>
</noscript>
<script type="text/javascript">
document.write('You are using <span style="font-weight: bold">Chat</span>.');
</script> Click to enter <span style="font-weight: normal">Messaging</span> <img src="images/ui/question.png" width="13" height="13" style="vertical-align: -1px;" title="differences: click-to-send, manual refresh, manual scroll, multiple lines possible, delete single messages, see if message is unread"></li>
</ul>
</div>
<div class="container">
<!-- BOX -->
<div class="box">
<div class="header">
<div style="z-index: 10; position: absolute; left: 88%; margin-top: 8px; width: 135px; height: 25px; border: 0px solid black;">nuke conversation</div>
<h4><img src="images/avatars/user1.png" width="14" height="14" style="vertical-align: -2px;"> bluebear</h4>
</div>
<div class="content">
<!-- jChat -->
<ul class="messages-layout">
<li class="messages"></li>
</ul>
<!-- Enter message field -->
<span class="session_time">Online</span><span id="sample"></span>
<div class="message-entry">
<input type="text" id="text-input-field" class="input-sm" name="message-entry" />
<div class="send-group">
<input type="submit" name="send-message" id="sendMessage" class="btn btn-primary" value="Send" />
</div>
</div>
<!-- Emoticons Modal -->
<div id="emoticons" class="modal hide fade">
<div class="modal-header"><h4>Emotions</h4></div>
<div class="modal-body"></div>
<div class="modal-footer">
Close
</div>
</div>
<!-- // jChat -->
</div>
</div>
<!-- // END BOX -->
</div>
</body>
<script>
$().Chat();
</script>
</html>
How can I fix it? Do you have any idea to solve it??
Thank you for the attention!
I solved the issue.
For all those who have problems similar to this, due to particular html codes, I recommend using robobrowser, a smart cross-platform module
(useful documentation here).
If for some reason you can not get the form of the page:
Try to specify the id of the form, like:
browser = RoboBrowser(id='FormId')
Try to pass headers with requests module:
import requests
mysession = requests.session()
open = mysession.get('website_url')
print(open.headers)
Add headers like so:
mysession.headers = open.headers
browser = RoboBrowser(id='FormId', session=mysession, history=True)
Hope it helps!

Categories

Resources