Cannot Seem to Find issue - python

I have been working on my company website in flask and I am trying to make the contact page work with URL_FOR, however it does not seem to be accepting it. I am not sure where I have gone wrong with the code. I am sure I am missing something or did something wrong. I have been working at this most of the morning. If anyone is able to help out that would be awesome..
Thank you in advance.
Michael
from flask import Flask, render_template, request, redirect, url_for
import csv
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/<string:page_name>')
def html_page(page_name):
return render_template(page_name)
# def write_to_file(data):
# with open('database.txt', mode='a') as database:
# name = data["name"]
# email = data["email"]
# message = data["message"]
# file = database.write(f'\n{name},{email},{message}')
def write_to_csv(data):
with open('database.csv', newline="", mode='a') as database2:
name = data["name"]
email = data["email"]
message = data["message"]
csv_writer = csv.writer(database2, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
csv_writer.writerow([name, email, message])
#app.route('/contact', methods=['POST', 'GET'])
def contact():
if request.method == 'POST':
data = request.form.to_dict()
write_to_csv(data)
return redirect('/sent.html')
else:
return 'Something went wrong. Try again..!'
html contact page is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Guru Coding | Contact Us</title>
<meta name="description"
content="Guru Coding services. We design and develop high quality websites tailored to your needs">
<link rel="icon" type="image/png" href="static/assets//favicon.png" />
<link rel="stylesheet" href="static/style/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css"
integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w=="
crossorigin="anonymous" />
</head>
<body>
<!-- Navigation container -->
<nav id='navMenu'>
<!-- Top Nav wrapper -->
<div class="top__nav__wrapper">
<!-- Logo container -->
<a href="index.html">
<div class="logo__container" title='Guru Coding logo'>
<!-- Logo -->
<img class='logo' src="static/assets/favicon.png" loading='lazy' alt="Guru Coding logo">
</div>
</a>
</div>
<!-- Nav list container -->
<div class="nav__list__container">
<ul>
<li title='Home'>Home</li>
<li title='Services'>Services</li>
<!-- <li title='Portfolio'>Portfolio</li> -->
<li title='Our Team'>Our Team</li>
<li title='Contact' class='page--active'>Contact</li>
</ul>
</div>
</nav>
<!-- Burger icon container -->
<div class="burger__container" id='navIcon'>
<!-- Burger lines -->
<div class="burger__line line1"></div>
<div class="burger__line line2"></div>
<div class="burger__line line3"></div>
</div>
<!-- Header container -->
<header>
<!-- Header text container -->
<div class="text__container">
<!-- Header title container -->
<div class="header__container header__container--contact">
<h1 class='highlight__title'>Contact Us</h1>
</div>
<!-- Header text container -->
<div class="header__text">
<!-- Header text -->
<h4>You have a business idea and you want to make it a <span class="highlight__text">real
thing?</span>
<br>
<br>
Or maybe you want a simple website for your <span class="highlight__text">personal needs?</span>
<br>
<br>
Whatever it is you
are looking for, you can surely find it at
<span class="highlight__text">Guru Coding!</span>
</h4>
</div>
</div>
<!-- Scroll icon container -->
<div class="icon__container">
<!-- Scroll icon -->
<i class="fas fa-sort-down"></i>
</div>
</header>
<!-- Section 1 container -->
<section class='section--1 section--contact'>
<h2 class='section__title'>Get in touch</h2>
<!-- Social Media icons container -->
<div class="social__icons__container">
<!-- Twitter link and icon -->
<a href="https://twitter.com/GuruCodingCo" title='Guru Coding Twitter' target="_blank">
<i class="fab fa-twitter-square"></i>
</a>
<!-- Facebook link and icon -->
<a href="https://www.facebook.com/Guru-Coding-Company-101417465307382" title='Guru Coding Facebook'
target="_blank">
<i class="fab fa-facebook-square"></i>
</a>
</div>
<!-- Contact form container -->
<div class="contact__form__container">
<form method="post" action="{{ url_for ('sent') }}" id='contactForm'>
<div class="input__container">
<label for="name">Name</label>
<input type="text" id='name' placeholder='Name'>
</div>
<div class="input__container">
<label for="email">Email</label>
<input type="text" id='email' placeholder='Email'>
</div>
<div class="input__container">
<textarea type="text" placeholder='Enter your message'></textarea>
</div>
<div class="button__container">
<button type='submit' id='submitButton' style='color: whitesmoke'>Submit</button>
</div>
</form>
</div>
</section>
<!-- Footer section -->
<footer>
<!-- Footer left -->
<div class="footer--left">
<p>Guru Coding 2021</p>
<br>
<a href="sitemap.html" class='highlight__link' title='Sitemap'>View Sitemap</a>
</div>
<!-- Footer right -->
<div class="footer--right">
<p>Website created by
<a title='Contact Author' class='highlight__link' href="mailto:lpytel16#gmail.com">Lukasz</a>
</p>
</div>
</footer>
<!-- Script tags -->
<script src="static/app.js"></script>
</body>
</html>

The problem here is you dont have a route for 'sent' anywhere in your code so I think you meant 'contact' for the form post method.

Related

(Python html) write python result in html, face simple layout error

the python script can rewrite all content of specify .html (in this case is "simple_website.html"), and showing the data extract from mysql
.py
import mysql.connector
import webbrowser
import time
mydb = mysql.connector.connect(
host="196.100.100.141",
user="root",
password="password456",
database="database_db",
auth_plugin='mysql_native_password'
)
mycursor = mydb.cursor()
mycursor.execute("SELECT row_01 FROM first_db")
myresult = mycursor.fetchall()
list_01 = []
for row in myresult:
temp_val = row[0]
list_01.append(temp_val)
print(list_01[5]) # get specific data from MySQL
html_content = f"<html><h1>this is the data extract from mysql:{list_01[5]} </h1></html>"
with open("simple_website.html","w") as html_file:
html_file.write(html_content) # show specific data on website
time.sleep(2)
webbrowser.open_new_tab("simple_website.html")
the output website pic with this logic
Q: if I just want to insert/replace "extract data (from mysql)" to certain area, how can I do so?
such as I just want to change the title , or part of the content in website, with "extract data"
original .html file (works fine)
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Rayson Technology - Your best OEM/ODM partner for Bluetooth solution</title>
<meta name="description" content=" content, we are the best company">
<meta name="keywords" content="content, where thestory begin" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Favicon -->
<link rel="icon" href="../images/favicon.png">
<!-- CSS ============================================ -->
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="../assets/css/vendor/bootstrap.min.css">
<!-- Font Family CSS -->
<link rel="stylesheet" href="../assets/css/vendor/cerebrisans.css">
<!-- FontAwesome CSS -->
<link rel="stylesheet" href="../assets/css/vendor/fontawesome-all.min.css">
<link rel="stylesheet" href="../assets/css/vendor/linea-icons.css">
<!-- Swiper slider CSS -->
<link rel="stylesheet" href="../assets/css/plugins/swiper.min.css">
<!-- animate-text CSS -->
<link rel="stylesheet" href="../assets/css/plugins/animate-text.css">
<!-- Animate CSS -->
<link rel="stylesheet" href="../assets/css/plugins/animate.min.css">
<!-- Light gallery CSS -->
<link rel="stylesheet" href="../assets/css/plugins/lightgallery.min.css">
<!-- Main Style CSS -->
<link rel="stylesheet" href="../assets/css/Custom.css">
<link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
<div class="preloader-activate preloader-active open_tm_preloader">
<div class="preloader-area-wrap">
<div class="spinner d-flex justify-content-center align-items-center h-100">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
<!-- Header Bottom Wrap Start -->
<div class="header-bottom-wrap header-sticky">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="header default-menu-style position-relative">
<!-- brand logo -->
<div class="header__logo">
<a href="index.html">
<img src="../images/logo.png" width="160" height="48" class="img-fluid" alt="">
</a>
</div>
<!-- header midle box -->
<div class="header-midle-box">
<div class="header-bottom-wrap d-md-block d-none">
<div class="header-bottom-inner">
<div class="header-bottom-left-wrap">
<!-- navigation menu -->
<div class="header__navigation d-none d-xl-block">
<nav class="navigation-menu primary--menu">
<ul>
<li class="has-children has-children--multilevel-submenu">
<span>Products</span>
<ul class="submenu">
<li><span>Nordic</span></li>
<li><span>product_02</span></li> <!-- # the line I want to change with mysql data -->
<li><span>product_03</span></li>
</ul>
</li>
<li>
<span>Software Support</span>
</li>
<li>
<span>Customization</span>
</li>
<li>
<span>Success Stories</span>
</li>
<li>
<span>Contact</span>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
<!-- header right box -->
<div class="header-right-box">
<div class="header-right-inner" id="hidden-icon-wrapper">
<!-- language-menu -->
<div class="language-menu">
<ul>
<li>
<a href="#" class="">
<span class="wpml-ls-native">English</span>
</a>
<ul class="ls-sub-menu">
<li class="">
<a href="../chinese/" class="">
<span class="wpml-ls-native">繁體中文</span>
</a>
</li>
<li class="">
<a href="../schinese/" class="">
<span class="wpml-ls-native">簡體中文</span>
</a>
</li>
</ul>
</li>
</ul>
</div>
<!-- header-search-form -->
<div class="header-search-form default-search">
<form action="search.html" class="search-form-top">
<input class="search-field" type="text" placeholder="Search…">
<button class="search-submit">
<i class="search-btn-icon fa fa-search"></i>
</button>
</form>
</div>
</div>
<div class="footer-copyright-area section-space--ptb_15">
<div class="container-fluid">
<div class="row align-items-center">
<div class="col-md-6 text-center text-md-start">
<!-- breadcrumb-list start -->
<ul class="breadcrumb-list">
<li class="breadcrumb-item">Home</li>
<li class="breadcrumb-item">Products</li>
<li class="breadcrumb-item active">Nordic</li>
</ul>
<!-- breadcrumb-list end -->
</div>
<div class="col-md-6 text-center text-md-end">
<span class="copyright-text">© 2022 sam_JR Technology co.,Ltd. All Rights Reserved.</span>
</div>
</div>
</div>
</div>
</div>
<!--==================== End of footer area ====================-->
</body>
</html>
idea: that I put the original html code with html_content = f" , and the old content will replace with {list_01[5]} , it should works fine, as the above logic showing, what do I need to change for code
I did
put original website html into .py script in html_content = f"
replace the old content with extract mysql data {list_01[5]} , in line 109
tried in .py script
import mysql.connector
import webbrowser
import time
mydb = mysql.connector.connect(
host="196.100.100.141",
user="root",
password="password456",
database="database_db",
auth_plugin='mysql_native_password'
)
mycursor = mydb.cursor()
mycursor.execute("SELECT row_01 FROM first_db")
myresult = mycursor.fetchall()
list_01 = []
for row in myresult:
temp_val = row[0]
list_01.append(temp_val)
print(list_01[5]) # get specific data from MySQL
html_content = f"<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Rayson Technology - Your best OEM/ODM partner for Bluetooth solution</title>
<meta name="description" content=" content, we are the best company">
<meta name="keywords" content="content, where thestory begin" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Favicon -->
<link rel="icon" href="../images/favicon.png">
<!-- CSS ============================================ -->
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="../assets/css/vendor/bootstrap.min.css">
<!-- Font Family CSS -->
<link rel="stylesheet" href="../assets/css/vendor/cerebrisans.css">
<!-- FontAwesome CSS -->
<link rel="stylesheet" href="../assets/css/vendor/fontawesome-all.min.css">
<link rel="stylesheet" href="../assets/css/vendor/linea-icons.css">
<!-- Swiper slider CSS -->
<link rel="stylesheet" href="../assets/css/plugins/swiper.min.css">
<!-- animate-text CSS -->
<link rel="stylesheet" href="../assets/css/plugins/animate-text.css">
<!-- Animate CSS -->
<link rel="stylesheet" href="../assets/css/plugins/animate.min.css">
<!-- Light gallery CSS -->
<link rel="stylesheet" href="../assets/css/plugins/lightgallery.min.css">
<!-- Main Style CSS -->
<link rel="stylesheet" href="../assets/css/Custom.css">
<link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
<div class="preloader-activate preloader-active open_tm_preloader">
<div class="preloader-area-wrap">
<div class="spinner d-flex justify-content-center align-items-center h-100">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
<!-- Header Bottom Wrap Start -->
<div class="header-bottom-wrap header-sticky">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="header default-menu-style position-relative">
<!-- brand logo -->
<div class="header__logo">
<a href="index.html">
<img src="../images/logo.png" width="160" height="48" class="img-fluid" alt="">
</a>
</div>
<!-- header midle box -->
<div class="header-midle-box">
<div class="header-bottom-wrap d-md-block d-none">
<div class="header-bottom-inner">
<div class="header-bottom-left-wrap">
<!-- navigation menu -->
<div class="header__navigation d-none d-xl-block">
<nav class="navigation-menu primary--menu">
<ul>
<li class="has-children has-children--multilevel-submenu">
<span>Products</span>
<ul class="submenu">
<li><span>Nordic</span></li>
<li><span>{list_01[5]}</span></li> <!-- # the line I want to change with mysql data -->
<li><span>product_03</span></li>
</ul>
</li>
<li>
<span>Software Support</span>
</li>
<li>
<span>Customization</span>
</li>
<li>
<span>Success Stories</span>
</li>
<li>
<span>Contact</span>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
<!-- header right box -->
<div class="header-right-box">
<div class="header-right-inner" id="hidden-icon-wrapper">
<!-- language-menu -->
<div class="language-menu">
<ul>
<li>
<a href="#" class="">
<span class="wpml-ls-native">English</span>
</a>
<ul class="ls-sub-menu">
<li class="">
<a href="../chinese/" class="">
<span class="wpml-ls-native">繁體中文</span>
</a>
</li>
<li class="">
<a href="../schinese/" class="">
<span class="wpml-ls-native">簡體中文</span>
</a>
</li>
</ul>
</li>
</ul>
</div>
<!-- header-search-form -->
<div class="header-search-form default-search">
<form action="search.html" class="search-form-top">
<input class="search-field" type="text" placeholder="Search…">
<button class="search-submit">
<i class="search-btn-icon fa fa-search"></i>
</button>
</form>
</div>
</div>
<div class="footer-copyright-area section-space--ptb_15">
<div class="container-fluid">
<div class="row align-items-center">
<div class="col-md-6 text-center text-md-start">
<!-- breadcrumb-list start -->
<ul class="breadcrumb-list">
<li class="breadcrumb-item">Home</li>
<li class="breadcrumb-item">Products</li>
<li class="breadcrumb-item active">Nordic</li>
</ul>
<!-- breadcrumb-list end -->
</div>
<div class="col-md-6 text-center text-md-end">
<span class="copyright-text">© 2022 sam_JR Technology co.,Ltd. All Rights Reserved.</span>
</div>
</div>
</div>
</div>
</div>
<!--==================== End of footer area ====================-->
</body>
</html>"
with open("simple_website.html","w") as html_file:
html_file.write(html_content) # show specific data on website
time.sleep(2)
webbrowser.open_new_tab("simple_website.html"
should be the same logic, just need to improve layout/format of try .py code

I made a login page ,After I put in the login credentials, the page is not moving to the next page

when I try to login to the page, it is not moving onto the next page. The project is linked to a db and the db stores the superuser data, but the login is not moving further
login_page.html :
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Student Management System | Log in</title>
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Font Awesome -->
<link rel="stylesheet" href="{% static "plugins/fontawesome-free/css/all.min.css" %}">
<!-- Ionicons -->
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<!-- icheck bootstrap -->
<link rel="stylesheet" href="{% static "plugins/icheck-bootstrap/icheck-bootstrap.min.css" %}">
<!-- Theme style -->
<link rel="stylesheet" href="{% static "dist/css/adminlte.min.css" %}">
<!-- Google Font: Source Sans Pro -->
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">
</head>
<body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
<b>Student</b> Management System
</div>
<!-- /.login-logo -->
<div class="card">
<div class="card-body login-card-body">
<p class="login-box-msg">Sign in to Student Management System</p>
<form action="/doLogin" method="post">
{% csrf_token %}
<div class="input-group mb-3">
<input type="email" class="form-control" placeholder="Email" name="email">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-envelope"></span>
</div>
</div>
</div>
<div class="input-group mb-3">
<input type="password" class="form-control" placeholder="Password" name="password">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
<div class="row">
<!-- /.col -->
<div class="col-12">
<button type="submit" class="btn btn-primary btn-block">Sign In</button>
</div><!-- /.col -->
</div>
</form>
<!-- /.social-auth-links -->
</div>
<!-- /.login-card-body -->
</div>
</div>
<!-- /.login-box -->
<!-- jQuery -->
<script src="{% static "plugins/jquery/jquery.min.js" %}"></script>
<!-- Bootstrap 4 -->
<script src="{% static "plugins/bootstrap/js/bootstrap.bundle.min.js" %}"></script>
<!-- AdminLTE App -->
<script src="{% static "dist/js/adminlte.min.js" %}"></script>
</body>
</html>
urls.py :
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls.static import static
from student_management_app import views
from student_management_system import settings
urlpatterns = [
url('demo',views.showDemoPage),
url(r'^admin/', admin.site.urls),
url('',views.ShowLoginPage),
url('doLogin',views.doLogin),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)+static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
The doLogin function is supposed to output the login credentials entered in the login page, but it is not going to the output part of it
views.py :
import datetime
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
def showDemoPage(request):
return render(request,"demo.html")
def ShowLoginPage(request):
return render(request,"login_page.html")
def doLogin(request):
if request.method != "POST":
return HttpResponse("<h2>Method not Allowed</h2>")
else:
return HttpResponse("Email : "+request.POST.get("email")+" Password : "+request.POST.get("password"))
one thing you can try to do is put a Login redirect URL in the settings.py file.
LOGIN_REDIRECT_URL = '/'

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 - my web application keep displaying "Hello World!"

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!

No CSS and JS, when slash at the end [duplicate]

This question already has answers here:
Link to Flask static files with url_for
(2 answers)
Closed 6 years ago.
Views.py
#app.errorhandler(404, strict_slashes=False)
def page_not_found(e):
return render_template('404.html', e=e)
404.html
{% extends 'layouts/layout1.html' %}
{% block title %}404 Page Not Found
{% endblock title %}
{% block content %}
<div class="container" >
<h3>Page you are looking for does not exist: {{ e }}</h3>
</div>
{% endblock %}
layout1.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">
<meta name="description" content="">
<meta name="author" content="">
<title>{% block title %}
{% endblock %}</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/small-business.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<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="#">
<img src="http://placehold.it/150x50&text=Logo" alt="">
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
About
</li>
<li>
Services
</li>
<li>
Contact
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- this is the data with the instruments, I applied on the top of hte website. -->
<div class="container" >
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active">Home</li>
<li role="presentation">Profile</li>
<li role="presentation">Messages</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane fade in active" id="home">
<ul>
<li>register</li>
<li>admin</li>
<li>Categories</li>
<li>much more crap here</li>
</ul>
</div>
<div role="tabpanel" class="tab-pane fade" id="profile">
TAB2
</div>
<div role="tabpanel" class="tab-pane fade" id="messages">
Tab 3
</div>
</div>
</div>
{% block content %}
{% endblock %}
<div class="container">
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-8">
<p>Copyright</p>
</div>
</div>
</footer>
</div>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
When I go to
http://127.0.0.1:5000/any_url_not_routed , like below,
it returns a 404 error as expected, but when I put a slash at the end,
http://127.0.0.1:5000/any_url_not_routed/ , like below,
it renders the same page but with no css and js.
Similar thing happens with other pages like /register, /login, etc. Also, browsers put automatic slash at the end.
Please tell me what is happening? I can link more code here.
Your "css/bootstrap.min.css" results in "/css/bootstrap.min.css" when the trailing slash is missing and "/any_url_not_routed/css/bootstrap.min.css" when the trailing slash is present.
You should use the absolute path "/css/bootstrap.min.css" for referencing resources, just as you already do for actions like "/register".
You can check the truth of this by looking at your server's request logs.

Categories

Resources