Page not found (404) Request Method: POST - python

I've been stuck with this error for a few days and am not able to find where the mistake is.
views section
from django.shortcuts import render,redirect
from django.contrib.auth.models import User,auth
# Create your views here.
def register(request):
if(request.method=='POST'):
username=request.POST['username']
password1=request.POST['password1']
password2=request.POST['password2']
user=User.objects.create_user(username=username,password=password1)
user.save();
print("user created")
return redirect('/')
else:
return render(request,'registration.html')
urls.py section
from django.urls import path
from . import views
urlpatterns=[path('register/',views.register,name="register")]
html section
<!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">
<title>Registration</title>
</head>
<body>
<form action="register" method="POST">
{% csrf_token %}
USERNAME <input type="text" name="username" id=""> <br><br>
PASSWORD <input type="password" name="password1" id=""> <br><br>
RETYPE PASSWORD <input type="password" name="password2" id=""> <br><br>
<input type="submit" value="">
</form>
</body>
</html>

Issue
create_user() doesn't require save() method to be called for creating instance.
You have given only action="register" which is not valid at all, you need to give url tag, to perfectly make route. That's the case for page not found which is the main question.
So, with some modifications try below code:
Views.py
def register(request):
if(request.method=='POST'):
username=request.POST['username']
password1=request.POST['password1']
password2=request.POST['password2']
user=User.objects.create_user(username=username,password=password1)
print("user created")
return redirect('/')
else:
return render(request,'registration.html')
Template file
<!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">
<title>Registration</title>
</head>
<body>
<form action="{% url 'register' %}" method="POST">
{% csrf_token %}
USERNAME <input type="text" name="username" id=""> <br><br>
PASSWORD <input type="password" name="password1" id=""> <br><br>
RETYPE PASSWORD <input type="password" name="password2" id=""> <br><br>
<input type="submit" value="Save">
</form>
</body>
</html>

Related

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

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

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

render template not changing the url of the page

I'm creating a login, register account website and it works well except for when i use the render template command as it loads the page successfully but then the url of the page is the URL of the previous page and when I refresh it, it goes back to the previous page. But when I use the redirect(url_for command I'm not able to pass variables through it
class LoginForm(FlaskForm):
username= StringField(validators=[InputRequired(),Length(min=4,max=20)],render_kw={"placeholder":"Username"})
password= PasswordField(validators=[InputRequired(),Length(min=8,max=20)],render_kw={"placeholder":"Password"})
submit =SubmitField("Login")
#app.route("/login",methods= ['GET','POST'])
def login():
form=LoginForm()
print("in login html")
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user:
if user.password==form.password.data:
login_user(user)
print("password entered")
userUsername=form.username.data
#return redirect(url_for('dashboard',userUser=userUsername,))
return render_template("dashboard.html",userUser=userUsername)
else:
print("incorrect pass")
return render_template("login.html",form=form)
#app.route("/dashboard",methods= ['GET','POST'])
#login_required
def dashboard():
return render_template("dashboard.html")
this is my python code, my dashboard.html-
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dashboard</title>
<link href = "../static/main.css" rel = "stylesheet">
</head>
<div class = "container1">
<body>
<div data-role="page" id="welcome" data-url="{{ url_for('dashboard') }}">
{%extends "layout.html"%}
{%block content%}
<p>{{userUser}}</p>
<h1>Hello you are logged in. </h1>
<div class = "container1">Welcome {{userUser}}!</div>
<form action ="{{url_for('login')}}" method = POST>
<br> <button type = "submit">Logout</button>
</form>
</div>
{%endblock%}
</body>
</html>
now my login.html
<!DOCTYPE html>
<html lang = "en">
<head>
<link href = "../static/main.css" rel = "stylesheet">
<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>Login</title>
</head>
<body>
<div class = "container">
<h1>Login</h1>
<form method="POST" actions="">
{{ form.hidden_tag() }}
{{ form.username }}
{{ form.password }}
{{ form.submit }}
</form>
Don't have an account? Sign Up
<div class = "message"> {{errorMessage | safe}}</div>
</div>
</body>
</html>
when i pass userUser through redirect(url_for it doesnt work but with render templates it does but the url remains /login

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().

Render_to_string and response.content.decode() not matching

I'm writing my first Django app by following along with this book:
http://chimera.labs.oreilly.com/books/1234000000754/ch05.html#_passing_python_variables_to_be_rendered_in_the_template
In the book there is a test that is verifying that the html is being returned as it is supposed to. Here is the test:
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
expected_html = render_to_string('home.html')
print(expected_html)
print(response.content.decode())
self.assertEqual(response.content.decode(), expected_html)
My test is failing on the assertEqual test because I have added a csrf token in my HTML using the Django Template Language. Here is what my HTML page looks like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do list</h1>
<form method="POST">
<input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>
{% csrf_token %}
</form>
<table id="id_list_table">
<tr><td>{{ new_item_list }}</td></tr>
</table>
</body>
</html>
My assert is failing due to the render_to_string method not including the token. Here is what my two print statements included in my test print out:
F<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do list</h1>
<form method="POST">
<input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>
</form>
<table id="id_list_table">
<tr><td></td></tr>
</table>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do list</h1>
<form method="POST">
<input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>
<input type='hidden' name='csrfmiddlewaretoken' value='VAiGvXZLHCjxWEWdjhgQRBwBSnMVoIWR' />
</form>
<table id="id_list_table">
<tr><td></td></tr>
</table>
</body>
</html>
F.
He doesn't have this problem in the book (he's using 1.8), so I was wondering if the method behavior has changed, or how I would write this test to pass.
The request argument was added to render_to_string in Django 1.8. You could try changing the line in your test to:
expected_html = render_to_string('home.html', request=request)
It's only required to make this change in Django 1.9+, the test passes without the request in Django 1.8.
I found this solution which has worked for the latest Django version - 3.0.6
#add a function to the post request test function
def remove_csrf_tag(text):
"""Remove csrf tag from TEXT"""
return re.sub(r'<[^>]*csrfmiddlewaretoken[^>]*>', '', text)
...
# then change assertion
def test_home_page_can_save_a_POST_request(self):
...
self.assertEqual(
remove_csrf_tag(response.content),
remove_csrf_tag(expected_html)
)

Categories