How to create a "simple" commentary section linked on a certain "ID" - python

I have a simple flask application that looks like that : MyFlaskAPP
the problem is i don't know if it's possible or not to add an "infinite amount" of comments and show them in the page of the software associated
for infos my list.html will be the interface for "admins" and list_user.html is the "user interface" because i don't want users to delete or modify thoses datas.
if somone could help me of give me somes tips btw here is my code :
app.py
from flask import Flask, render_template, redirect, url_for, request
from flask_sqlalchemy import SQLAlchemy
import time
# create the extension
db = SQLAlchemy()
# create the app
app = Flask(__name__)
# configure the SQLite database, relative to the app instance folder
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///web_solinest.db"
# initialize the app with the extension
db.init_app(app)
class Webapp(db.Model):
id = db.Column(db.Integer, primary_key=True)
nom = db.Column(db.String)
pastille = db.Column(db.String)
description = db.Column(db.String)
update_time = db.Column(
db.String, default=time.strftime("%m-%d-%Y %H:%M"))
with app.app_context():
db.create_all()
#app.route("/solistatus")
def show_all():
webapps = db.session.execute(
db.select(Webapp).order_by(Webapp.nom)).scalars()
return render_template("webapp/list_user.html", webapps=webapps)
#app.route("/admin")
def webapp_list():
webapps = db.session.execute(
db.select(Webapp).order_by(Webapp.nom)).scalars()
return render_template("webapp/list.html", webapps=webapps)
#app.route("/solistatus/create", methods=["GET", "POST"])
def webapp_create():
if request.method == "POST":
webapps = Webapp(
nom=request.form["nom"],
pastille=request.form["pastille"],
description=request.form["description"]
)
db.session.add(webapps)
db.session.commit()
return render_template("webapp/create.html")
#app.route("/solistatus/update/<int:id>", methods=["GET", "POST"])
def webapp_update(id):
webapp = Webapp.query.get(id)
if request.method == "POST":
webapp.nom = request.form["nom"]
webapp.pastille = request.form["pastille"]
webapp.description = request.form["description"]
webapp.update_time = time.strftime("%m-%d-%Y %H:%M")
db.session.commit()
return render_template("webapp/update.html", webapp=webapp)
#app.route("/solistatus/<int:id>/delete", methods=["GET"])
def webapp_delete(id):
webapps = Webapp.query.get(id)
db.session.delete(webapps)
db.session.commit()
return redirect(url_for('webapp_list'))
list.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.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght#300;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<title>Admin page</title>
</head>
<body>
<h3>Add Software</h3>
<table class="display_table">
<thead>
<tr>
<th style="width: 10px;">Pastille</th>
<th style="width: 300px;">Nom</th>
<th>ID</th>
</tr>
</thead>
<tbody>
{% for Webapp in webapps %}
<tr>
<td class="tiny"><img style="width: 40px;"
src="https://icones.pro/wp-content/uploads/2021/04/icone-cercle-rempli-{{Webapp.pastille }}.png"
style="width: 10%;" alt=""></td>
<td>{{ Webapp.nom }}</td>
<td>{{ Webapp.id }}</td>
<td>Delete</td>
<td>Update</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
create.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.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght#300;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<title>Create page</title>
</head>
<html>
<body>
<h3>Software creation</h3>
Home page<br>
<form action="{{ request.path }}" method="post">
<label for="pastille">Pastille</label><br>
<select type="text" name="pastille" id="pastille" class="form-control">
<option value="vert">Vert</option>
<option value="rouge">Rouge</option>
</select><br>
<label for="nom">Nom</label><br>
<input type="text" name="nom" placeholder="nom" /><br>
<label for="description">Description</label><br>
<textarea name="description" placeholder="description"></textarea><br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
update.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.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght#300;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<title>Create page</title>
</head>
<body>
<h1 id="homepage">Home page</h1><br>
<form method="post">
<div class="form-group">
<label for="nom">Nom</label>
<input type="text" class="form-control" id="nom" name="nom" value="{{ webapp.nom }}">
</div>
<div class="form-group">
<label for="pastille">Pastille</label>
<select type="text" name="pastille" id="pastille" class="form-control">
<option value="rouge">Rouge</option>
<option value="vert">Vert</option>
</select>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea type="text" class="form-control" id="description"
name="description">{{ webapp.description }}</textarea>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</body>
Thank you a lot if someone could help me or inform me I'm interested
i tried to create a new table called history but i don't know how to link the table 1 to the table 2 using the ID and display the comment section of the ID n°1

Related

When trying to pass in a post it is not working

<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.0" />
<title>Document</title>
</head>
<body>
<form method="POST">
{% csrf_token %} {{ form.as_p }}
<input type="submit" value="Submit" />
</form>
</body>
</html>
class Post(CreateView):
fields = ("title","about","itempicture")
template_name = "post.html"
model = models.Listing
I can't seem to figure out why is is not working my html and views connect perfectly put when try to send in a post request it does not work I would happy if someone could help me out
You should define your form in the view:
class Post(CreateView):
fields = ("title","about","itempicture")
template_name = "post.html"
model = models.Listing
form_class = YourForm

Blank page showing in django server after adding python in index.html file

Please help I'm following a tutorial and not showing desierd output in the server page.
Every thing was going smoothly until the index.html page content not shown.
This is my index.html file
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>
<title>document</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<div class="container">
<div class="row">
**{% for Product in product_objetcs %}**
<div class="col-md-3">
<div class="card">
<img src="{{ product.image }}" class="card-img-top">
<div class="card-body">
<div class="card-title">
**{{ product.tittle }}**
</div>
<div class="card-text">
**{{ product.price }}**
</div>
</div>
</div>
**{% endfor %}**
</div>
</div>
</div>
</body>
</html>
This my views page
from django.shortcuts import render
from.models import Product
# Create your views here.
def index(request):
product_objects = Product.objects.all()
return render(request,
My models page looks like this
from django.db import models
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=200)
price = models.FloatField()
discount_price = models.FloatField()
category = models.CharField(max_length=200)
description = models.TextField()
image = models.CharField(max_length=300)

Django How to make form fit HTML input field

I have a small question.
Here is my "Register page":
[![Register page][1]][1]
But when I add my form to the login, for example, I get this:
[![Page with login][2]][2]
I want to know how can I make that form box fit that HTML input field?
I don't know if I have to resize it in the forms.py or if there was a way for it to always bind up the input size that is in the HTML file.
This is the HTML:
{% load static %}
<!DOCTYPE html>
{% csrf_token %}
<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.0" />
<title>IPV QS Tool Registration</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous"
/>
<link rel="stylesheet" href="registration.css" />
<link rel="stylesheet" type="text/css" href="{% static 'css/style_register.css' %}" />
</head>
<body>
<form method="POST" action="">
<label>
<p class="label-txt">ENTER YOUR AMAZON EMAIL</p>
<input type="email" class="input" required />
<div class="line-box"></div>
<div class="line"></div>
</div>
</label>
<label>
<p class="label-txt">ENTER YOUR AMAZON LOGIN</p>
{{form.username}}
<div class="line-box">
<div class="line"></div>
</div>
</label>
<label>
<p class="label-txt">CREATE A PASSWORD</p>
<input
type="password"
class="input password"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters"
required
/>
<div class="line-box">
<div class="line"></div>
</div>
</label>
<button type="submit">Submit</button>
</form>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"
></script>
<script src="registration.js"></script>
</body>
</html>
Forms.py:
class createUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
It seems like you are missing class="input" from your input field. Please try this,
username = forms.CharField(max_length=100,
widget= forms.TextInput
(attrs={'class':'input'}))
widget= forms.TextInput(attrs={'class':'input'})
It will result in addition of this class to your CharField.
I hope this helps. Feel free to connect in case if the issue still persists.
Thanks.

How to connect my two HTML pages using flask

I am trying to link two html pages 'home.html' and 'result.html' using flask framework but it is not working. Also the changes that I make in html page are not reflecting when page is opened with flask.
Here's the code for 'home.html' :
<!doctype <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>IRIS PREDICTOR</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="/static/main.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://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>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
</head>
<body>
<h1 class="text-info">IRIS PREDICTION</h1>
<form action="/result" method="POST">
<div class="col-2" id="abc">
<label for="ex2">Sepal Length</label>
<input class="form-control" id="ex2" type="text" name="s_length">
</div>
<div class="col-2">
<label for="ex2">Sepal Width</label>
<input class="form-control" id="ex2" type="text" name="s_width">
</div>
<div class="col-2">
<label for="ex2">Petal Length</label>
<input class="form-control" id="ex2" type="text" name="p_length">
</div>
<div class="col-2">
<label for="ex2">Petal Width</label>
<input class="form-control" id="ex2" type="text" name="p_width">
</div>
<button class="btn btn-outline-secondary" type="button" id="button-addon1">Predict</button>
</form>
</body>
</html>
Code for 'result.html':
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>PREDICTION RESULT</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="/static/style.css" />
<script src="main.js"></script>
</head>
<body>
<p>Sepal Length: {{sepal_length}}</p>
<p>Sepal Width: {{sepal_width}}</p>
<p>Petal Length: {{petal_length}}</p>
<p>Petal Width: {{petal_width}}</p>
<p>Species: {{predict_result}}</p>
</body>
</html>
And code for script.py is:
from flask import Flask,render_template,request
from sklearn.externals import joblib
app=Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
#app.route('/predict',methods=['POST'])
def show():
if request.method=='POST':
sepal_length=request.form['s_length']
sepal_width=request.form['s_width']
petal_length=request.form['p_length']
petal_width=request.form['p_width']
data=[[float(sepal_length),float(sepal_width),float(petal_length),float(petal_width)]]
model=joblib.load('iris_model.pkl')
predict_result=model.predict(data)
return render_template('result.html',sepal_length=sepal_length,sepal_width=sepal_width,petal_length=petal_length,petal_width=petal_width,predict_result=predict_result)
if __name__=='__main__':
app.run(debug=True)
What should i do now?
I have your code working. Your #app.route for the show function was for /result but home.html was posting the data to /result/
Also your button on home.html wasn't a submit button so it never posted the form.
Full listings of the files below
script.py - i've commented out the joblib items
from flask import Flask,render_template,request
#from sklearn.externals import joblib
app=Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
#app.route('/predict',methods=['POST'])
def show():
if request.method=='POST':
sepal_length=request.form['s_length']
sepal_width=request.form['s_width']
petal_length=request.form['p_length']
petal_width=request.form['p_width']
data=[[float(sepal_length),float(sepal_width),float(petal_length),float(petal_width)]]
#model=joblib.load('iris_model.pkl')
#predict_result=model.predict(data)
predict_result="TEST"
return render_template('result.html',sepal_length=sepal_length,sepal_width=sepal_width,petal_length=petal_length,petal_width=petal_width,predict_result=predict_result)
if __name__=='__main__':
app.run()
home.html
<!doctype <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>IRIS PREDICTOR</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="/static/main.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://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>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
</head>
<body>
<h1 class="text-info">IRIS PREDICTION</h1>
<form action="/predict" method="POST">
<div class="col-2" id="abc">
<label for="ex2">Sepal Length</label>
<input class="form-control" id="ex2" type="text" name="s_length">
</div>
<div class="col-2">
<label for="ex2">Sepal Width</label>
<input class="form-control" id="ex2" type="text" name="s_width">
</div>
<div class="col-2">
<label for="ex2">Petal Length</label>
<input class="form-control" id="ex2" type="text" name="p_length">
</div>
<div class="col-2">
<label for="ex2">Petal Width</label>
<input class="form-control" id="ex2" type="text" name="p_width">
</div>
<button class="btn btn-outline-secondary" type="submit" id="button-addon1">Predict</button>
</form>
</body>
</html>
result.html is unchanged from your example
I hope the explanation below helps others in the future.
Please make sure that you save all 3 files in the same directory(folder). In the same folder you saved the script.py, create another folder and name it "templates". Place both html files in this folder. Then, run script.py in your terminal, you should see the output on the server.
Usually, the reason why changes are not reflecting in your page is because you might have forgotten to save the changes after they are made. One might think that it is automatically saved but it is not.
Put your both templates in 'templates' directory where your scripts.py located. Flask search template files in 'templates' directory.
Remove space between #app.route and def home().

How can I login to HTML login page with my email address in Django

I create a HTML login page and I authenticate it through views.py. I want to login with my email address only. But when I use other email addresses , I can able to login.I set custom_authentication in my views.py.
Template login.html
{% load staticfiles %}
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en"> <!--<![endif]-->
<head>
<title>S.P.M School</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link rel="stylesheet" href="css/style.css">
<!--[if lt IE 9]><script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<style>
table, th, td {
border: 0px solid black;
}
</style>
<script>
function validateForm() {
var mail = document.forms["myForm"]["email"].value;
var psd = document.forms["myForm"]["password"].value;
var atpos = mail.indexOf("#");
var dotpos = mail.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=mail.length) {
alert("Not a valid e-mail address");
return false;
}
if (psd == null || psd == "") {
alert("Not a valid Password");
return false;
}
}
</script>
</head>
<body>
<div id="page">
<div id="header">
<div id="section">
{% if user.is_authenticated %}
<span class="glyphicon glyphicon-plus"></span>
{% endif %}
<div class="headline">
<font size="10": color="white"><center>S.P.M.L.P School</center></font>
</div>
<span>303nishanth#gmail.com <br />
<br />
+91 9961685892</span> </div>
<ul>
<li class="#">Home</li>
<li>About Us</li>
<li>Event</li>
<li>School Calendar</li>
<li>Contact us</li>
</ul>
<br><br>
<section class="container">
<div class="login">
<div id="section"><br><br>
<h1><center>Login As<font color="red"> Admin</font></center></h1><br>
</div>
<form name="myForm" action="{% url 'class_info' %}" onsubmit="return validateForm();" method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='wu5eSIDElr8EsVDgXmHmFNCCmSLdhyK5' />
{%csrf_token%}
<div class="text">
<p><center><input type="text" name="email" placeholder="Username or Email"></p></center>
<p><center><input type="password" name="password" placeholder="Password"></p></center>
<p class="remember_me">
</p>
<center><p class="submit"><input type="submit" name="commit" value="Login"></p></center>
</form>
</div>
</section>
</body>
</html>
views.py
def login(request):
return render(request, 'blog/login.html')
def custom_auth(username=None, password=None):
user = None
if username == '303nishanth#gmail.com': # only this email is allowed
user = authenticate(username=email, password=psd)
return user
def login_submit(request):
context = {}
email = request.POST.get('email','')
psd = request.POST.get('password', '')
user = custom_auth(username=email, password=psd)
if user is not None:
# the password verified for the user
if user.is_active:
context['message'] = "User is valid, active and authenticated"
return render (request,'class_info.html',context)
else:
context['message']= "The password is valid, but the account has been disabled!"
else:
# the authentication system was unable to verify the username and password
context['message']= "The username and password were incorrect."
return render (request,'login.html',context)

Categories