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

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 }}">

Related

Cannot Seem to Find issue

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.

Handling Multiple Forms on the Same Page in Django without Django's default model form

I am trying to develop a webpage with two forms on the same page with Django. Anyone will able to fillup any single form and submit it, then that data will be saved in the database. Here I try to avoid Django's default model form and any type of js stuff also.
My HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<!-- animated css link -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.0.0/animate.min.css"/>
<!-- font awsome css link -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- custom css link -->
<link rel="stylesheet" type="text/css" href="#">
</head>
<body>
<div class="row m-0 bg-info">
<h2 class="mx-auto my-4">Multiple form in one page</h2>
</div>
<div style="height: 40px;"></div>
<div class="container-fluid my-5">
<div class="row m-0 d-flex justify-content-center">
<div class="col-md-3">
<h2>Employee Profile</h2>
<form class="#" method="POST" id="EmployeeProfile">
<div class="form-group">
<label>Ranks</label>
<input type="text" class="form-control" name="ranks" placeholder="Enter ranks">
</div>
<div class="form-group">
<label>salary</label>
<input type="text" class="form-control" name="salary" placeholder="Enter salary">
</div>
<div class="row d-flex justify-content-center">
<button type="submit" class="btn btn-primary m-2">Submit</button>
</div>
</form>
</div>
<div class="col-md-2"></div>
<div class="col-md-3">
<h2>Inspector Profile</h2>
<form class="#" method="POST" id="InspectorProfile">
<div class="form-group">
<label>Ranks</label>
<input type="text" class="form-control" name="ranks" placeholder="Enter ranks">
</div>
<div class="form-group">
<label>Your email</label>
<input type="email" class="form-control" name="email" placeholder="email">
</div>
<div class="row d-flex justify-content-center">
<button type="submit" class="btn btn-primary m-2">Submit</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Here how can I code my views.py with function based view to get data from this form? and how to determine which form sent me that data.
You can do that by setting different form action and by making different view for perticular form like this
inside your template :
<form method="POST" action="{% url 'form1' %}">
........all input fields
</form>
<form method="POST" action="{% url 'form2' %}">
........all input fields
</form>
inside your views.py :
def form1(request):
if request.method == "POST":
...get all values
return render(request,'forms.html')
def form2(request):
if request.method == "POST":
...get all values
return render(request,'forms.html')

Why the Models not showing up in django website

I am making a news website and i have made a model of an image, title, description,url(for clickable image), but the final output is not just showing up and there is no error .
Please also look into image links I have attached The output Screenshot and The admin Page screenshot
Main Code
{% load static %}
{% block content %}
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>World Vision</title>
<!-- plugin css for this page -->
<link
rel="stylesheet"
href="{% static 'techworld/assets/vendors/mdi/css/materialdesignicons.min.css' %}"
/>
<link rel="stylesheet" href="{% static 'techworld/assets/vendors/aos/dist/aos.css/aos.css' %}" />
<link
rel="stylesheet"
href="{% static 'techworld/assets/vendors/owl.carousel/dist/assets/owl.carousel.min.css' %}"
/>
<link
rel="stylesheet"
href="{% static 'techworld/assets/vendors/owl.carousel/dist/assets/owl.theme.default.min.css' %}"
/>
<!-- End plugin css for this page -->
<link rel="shortcut icon" href="{% static 'techworld/assets/images/favicon.png' %}" />
<!-- inject:css -->
<link rel="stylesheet" href="{% static 'techworld/assets/css/style.css' %}">
<!-- endinject -->
<!-- Bootstrap -->
<link href="{% static 'techworld/box/css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'techworld/box/ionicons/css/ionicons.min.css' %}" rel="stylesheet">
<!-- main css -->
<link href="{% static 'techworld/box/css/style.css' %}" rel="stylesheet">
<!-- modernizr -->
<script src="{% static 'techworld/box/js/modernizr.js' %}"></script>
<link
rel="stylesheet"
href="{% static 'techworld/worldtime/assets/vendors/mdi/css/materialdesignicons.min.css' %}"
/>
<link rel="stylesheet" href="{% static 'techworld/worldtime/assets/vendors/aos/dist/aos.css/aos.css' %}" />
<!-- End plugin css for this page -->
<link rel="shortcut icon" href="{% static 'techworld/worldtime/assets/images/favicon.png' %}" />
<!-- inject:css -->
<link rel="stylesheet" href="{% static 'techworld/worldtime/assets/css/style.css' %}">
<!-- endinject -->
<title>Tech-World</title>
</head>
<body>
<!-- Preloader -->
<div id="preloader">
<div class="pre-container">
<div class="spinner">
<div class="double-bounce1"></div>
<div class="double-bounce2"></div>
</div>
</div>
</div>
<!-- end Preloader -->
<!-- Intro Slide
<div class="container-fluid">
<section class="box-intro">
<div class="table-sell">
<h1 class="box-headline letters rotate-2">
<span class="box-words-wrapper">
<b class="is-visible">Choose What you Read</b>
<b> To see all the latest talks Scroll down</b>
</span>
</h1>
<h5>More than everything You need</h5>
</div>
<div class="mouse">
<div class="scroll"></div>
</div>
</section>
</div>-->
<!-- End Intro slide -->
<div class="container-fluid">
<!-- box header -->
<!-- end box header -->
<!-- box-intro -->
<section class="box-intro">
<div class="table-cell">
<h1 class="box-headline letters rotate-2">
<span class="box-words-wrapper">
<b class="is-visible">design. mbkm</b>
<b> coding.</b>
<b>graphic.</b>
</span>
</h1>
<h5>We always server more than everythin you need </h5>
</div>
<div class="mouse">
<div class="scroll"></div>
</div>
</section>
<!-- end box-intro -->
</div>
<!-- portfolio div -->
<div class="portfolio-div">
<div class="portfolio">
<div class="no-padding portfolio_container">
<!-- single work -->
<div class="col-md-3 col-sm-6 fashion logo">
<a href="single-project.html" class="portfolio_item">
<img src="{% static 'techworld/img/apple.png' %}" alt="image" class="img-responsive" />
<div class="portfolio_item_hover">
<div class="portfolio-border clearfix">
<div class="item_info">
<span>Latest Talks from Apple</span>
<em>Apple TechWorld</em>
</div>
</div>
</div>
</a>
</div>
<!-- end single work -->
<div class="col-md-3 col-sm-6 ads graphics">
<a href="#" class="portfolio_item">
<img src="{% static 'techworld/img/tablet.png' %}" alt="image" class="img-responsive" />
<div class="portfolio_item_hover">
<div class="portfolio-border clearfix">
<div class="item_info">
<span>Latest Productivity Tablets</span>
<em>Latest Tablets</em>
</div>
</div>
</div>
</a>
</div>
<div class="col-md-6 col-sm-12 photography">
<a href="#" class="portfolio_item">
<img src="{% static 'techworld/img/mobile.jpg' %}" alt="image" class="img-responsive" />
<div class="portfolio_item_hover">
<div class="portfolio-border clearfix">
<div class="item_info">
<span>Its all About SmartPhones</span>
<em>Reviews,Latest news and much more</em>
</div>
</div>
</div>
</a>
</div>
<!-- Single workflow area end -->
<!-- Dual workflow area part 2 -->
<div class="col-md-3 col-sm-6 fashion ads">
<a href="#" class="portfolio_item">
<img src="{% static 'techworld/img/samsung.png' %}" alt="image" class="img-responsive" />
<div class="portfolio_item_hover">
<div class="portfolio-border clearfix">
<div class="item_info">
<span>Empty space</span>
<em>Empty space</em>
</div>
</div>
</div>
</a>
</div>
<div class="col-md-3 col-sm-6 graphics ads">
<a href="#" class="portfolio_item">
<img src="{% static 'techworld/img/samsung.png' %}" alt="image" class="img-responsive" />
<div class="portfolio_item_hover">
<div class="portfolio-border clearfix">
<div class="item_info">
<span>Empty space</span>
<em>Empty space</em>
</div>
</div>
</div>
</a>
</div>
<div class="col-md-6 col-sm-12 photography">
<a href="#" class="portfolio_item">
<img src="{% static 'techworld/img/samsung.png' %}" alt="image" class="img-responsive" />
<div class="portfolio_item_hover">
<div class="portfolio-border clearfix">
<div class="item_info">
<span>Empty space</span>
<em>Empty space</em>
</div>
</div>
</div>
</a>
</div>
<div class="col-md-3 col-sm-6 graphics ads">
<a href="#" class="portfolio_item">
<img src="{% static 'techworld/img/samsung.png' %}" alt="image" class="img-responsive" />
<div class="portfolio_item_hover">
<div class="portfolio-border clearfix">
<div class="item_info">
<span>Empty space</span>
<em>Empty space</em>
</div>
</div>
</div>
</a>
</div>
<div class="col-md-3 col-sm-6 graphics ads">
<a href="#" class="portfolio_item">
<img src="{% static 'techworld/img/samsung.png' %}" alt="image" class="img-responsive" />
<div class="portfolio_item_hover">
<div class="portfolio-border clearfix">
<div class="item_info">
<span>Empty space</span>
<em>Empty space</em>
</div>
</div>
</div>
</a>
</div>
<div class="col-md-3 col-sm-6 graphics ads">
<a href="#" class="portfolio_item">
<img src="{% static 'techworld/img/samsung.png' %}" alt="image" class="img-responsive" />
<div class="portfolio_item_hover">
<div class="portfolio-border clearfix">
<div class="item_info">
<span>Empty space</span>
<em>Empty space</em>
</div>
</div>
</div>
</a>
</div>
<div class="col-md-3 col-sm-6 graphics ads">
<a href="#" class="portfolio_item">
<img src="{% static 'techworld/img/samsung.png' %}" alt="image" class="img-responsive" />
<div class="portfolio_item_hover">
<div class="portfolio-border clearfix">
<div class="item_info">
<span>Empty space</span>
<em>Empty space</em>
</div>
</div>
</div>
</a>
</div>
</div>
<!-- end portfolio_container -->
</div>
<!-- portfolio -->
</div>
<!-- end portfolio div -->
<br>
<br>
<br>
<div class="container-scroller">
<div class="main-panel">
<!-- partial:partials/_navbar.html -->
<!-- partial -->
<div class="content-wrapper">
<div class="container">
<div class="row" data-aos="fade-up">
{% for AllProject in allprojects %}
<div class="col-xl-8 stretch-card grid-margin">
<div class="position-relative">
{% if AllProject.url %}
<a href="{{ AllProject.url }}"><img
src="{{ AllProject.image.url }}"
alt="banner"
class="img-fluid" />
</a>
{% else %}
<img src="{{ AllProject.image.url }}" alt="banner" class="img-fluid" />
{% endif %}
<div class="banner-content">
<div class="badge badge-danger fs-12 font-weight-bold mb-3">
global news
</div>
<h1 class="mb-0">{{ AllProject.title }}</h1>
<h1 class="mb-2">
{{ AllProject.description }}
</h1>
<div class="fs-12">
<span class="mr-2">Photo </span>10 Minutes ago
</div>
</div>
</div>
</div>
{% endfor %}
</div>
<div class="row" data-aos="fade-up">
<div class="col-lg-3 stretch-card grid-margin">
<div class="card">
<div class="card-body">
<h2>Category</h2>
<ul class="vertical-menu">
<li>Politics</li>
<li>International</li>
<li>Finance</li>
<li>Health care</li>
<li>Technology</li>
<li>Jobs</li>
<li>Media</li>
<li>Administration</li>
<li>Sports</li>
<li>Game</li>
<li>Art</li>
<li>Kids</li>
</ul>
</div>
</div>
</div>
<div class="col-lg-9 stretch-card grid-margin">
<div class="card">
<div class="card-body">
{% for Flash in flashes %}
<div class="row">
<div class="col-sm-4 grid-margin">
<div class="position-relative">
<div class="rotate-img">
{% if Flash.url %}
<a href="{{ Flash.url }}">
<img src="{{ project.image.url }}" alt="thumb" class="img-fluid" />
</a>
{% else %}
<img src="{{ project.image.url }}" alt="thumb" class="img-fluid" />
{% endif %}
</div>
<div class="badge-positioned">
<span class="badge badge-danger font-weight-bold"
>Flash news</span
>
</div>
</div>
</div>
<div class="col-sm-8 grid-margin">
<h2 class="mb-2 font-weight-600">
{{ Flash.title }}
</h2>
<div class="fs-13 mb-2">
<span class="mr-2">Photo </span>10 Minutes ago
</div>
<p class="mb-0">
{{ Flash.description }}
</p>
</div>
</div>
{% endfor %}
{% endblock %}
</div>
</div>
</div>
</div>
Views.py
from django.shortcuts import render
from .models import AllProject
from .models import Flash
def techhome(request):
allprojects = AllProject.objects.all()
return render(request, 'techworld/techhome.html', {'allprojects':allprojects})
def Flashnews(request):
flashes = Flash.objects.all()
return render(request, 'techworld/techhome1.html', {'flashes':flashes})
Models.py
from django.db import models
class AllProject(models.Model):
title = models.CharField(max_length=100)
description = models.CharField(max_length=250)
image = models.ImageField(upload_to='techworld/images/')
url = models.URLField(blank=True)
date = models.DateField(blank=True)
def __str__(self):
return self.title
class Flash(models.Model):
title = models.CharField(max_length=100)
description = models.CharField(max_length=250)
image = models.ImageField(upload_to='techworld/images/')
url = models.URLField(blank=True)
date = models.DateField(blank=True)
def __str__(self):
return self.title
Please also look into image links I have attached The output Screenshot and The admin Page screenshot
You are using both allprojects and flashes in your template, but you pass them in separate views to different templates.
It's not clear (to me, at least) which of these views corresponds to this template. I'm guessing you're trying to use the techhome() view, since you appear to be unable to get the Flash data to appear. You'll need to pass both allprojects and flashes as context to the template so they can be rendered. If, for example, you wish techhome() to display both, you could do the following:
def techhome(request):
allprojects = AllProject.objects.all()
flashes = Flash.objects.all()
context = {'allprojects':allprojects, 'flashes':flashes}
return render(request, 'techworld/techhome.html', context)

404 Error in flask webapp unable to find reason

When running the webapp a 404 error appears, the error doesnt even allow my error html to run even when changing it to the most basic of templates. I dont know where my request is being not found.
Ive tried removing all of the style sheets from base.html to see if its those, I tried changing the error.html to see if it will actually run I've attempted to comment out all url_for's in the html files.
I commented out the results bit so i dont think its that.
routes.py
from app import app
from flask import Flask, abort, jsonify, redirect, url_for, request, render_template
from werkzeug.exceptions import HTTPException
from app.results import clean_data, get_response
#app.errorhandler(Exception)
def handle_error(e):
'''
code = 500
if isinstance(e, HTTPException):
code = e.code'''
print(str(e))
return render_template("error.html")
#app.route('/', methods=['GET', 'POST'])
def index():
data = clean_data(request.form)
response = get_response(data)
print(response)
return render_template("index.html")
base.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Default Scorer -- Ebury</title>
<meta name = "viewport" content = "width=device-width", initial-scale = 1, shrink-to-fit=no">
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}">
<!-- CSS-->
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<link href="https://fonts.googleapis.com/css?family=Roboto:100" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- JS-->
<!-- [if lt IE 9]><script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js" type="text/javascript"></script><![endif] -->
<script src="https://ebury-chameleon.s3.amazonaws.com/1.17.0/scripts/ebury-chameleon.js" type="text/javascript"></script>
</head>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="/">
<img src="{{ url_for('static', filename='img/Ebury.png') }}" width="80" height="30" alt="">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-item nav-link active" href="/"><b>Default Scorer</b> <span class="sr-only">(current)</span></a>
</div>
<div class="navbar-nav ml-auto">
<a class="nav-item nav-link" href="/logout">Log out</a>
</div>
</div>
</nav>
<body>
</body>
</html>
index.html(only relevant parts its got a lot of forms)
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block content %}
<div class="m-1 pb-3"></div>
<div class="container-fluid">
<div class = "row">
<div class="col-md-3 push-md-3">
<div class = "m-0 pb-0">
<form action="" method="post" role="form" class="needs-validation" novalidate>
<div class="container">
<div class = "form-group">
<div class = "row">
<div class="input-group input-group-sm mb-3">
<div class="input-group-prepend">
<span class = "input-group-text">BVD ID Number</span>
</div>
<input type = "text" class = "form-control" id = "bvd_id_number" name = "bvd_id_number">
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script>
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
{% endblock %}
error.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ERROR</title>
</head>
<body>
<h1>ERROR</h1>
</body>
</html>
So what happens is that the form doesnt appear and it seems only base.html appears with nothing else, the icon doesnt appear either but I tried commenting that out and that doesnt work.
The error printed is "404 Not Found: The requested URL was not found on the server. IF you entered the URL manually please check your spelling and try again"
To future people: I solved because the base.html did not specify where it had to be extended. The correct base.html code would be:
<html>
<head>
<meta charset="utf-8">
<title>Default Scorer -- Ebury</title>
<meta name = "viewport" content = "width=device-width", initial-scale = 1, shrink-to-fit=no">
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}">
<!-- CSS-->
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<link href="https://fonts.googleapis.com/css?family=Roboto:100" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- JS-->
<!-- [if lt IE 9]><script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js" type="text/javascript"></script><![endif] -->
<script src="https://ebury-chameleon.s3.amazonaws.com/1.17.0/scripts/ebury-chameleon.js" type="text/javascript"></script>
</head>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="/">
<img src="{{ url_for('static', filename='img/Ebury.png') }}" width="80" height="30" alt="">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-item nav-link active" href="/"><b>Default Scorer</b> <span class="sr-only">(current)</span></a>
</div>
<div class="navbar-nav ml-auto">
<a class="nav-item nav-link" href="/logout">Log out</a>
</div>
</div>
</nav>
<body>
{% block content %}
{% endblock %}
</body>
{% block scripts %}
{% endblock %}
</html>```

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)

Categories

Resources