If from begining i start with Register Page it work ,but if i use,int html, a hyperlink to the Register page it will stop working and print(405 Method Not Allowed/The method is not allowed for the requested URL.).
Here is my python code except run and imports:
And i use python 3.8
app = Flask(__name__)
#app.route("/")
def main():
return render_template("MainFacut.html")
#app.route("/register")
def register():
return render_template("Register.html")
#app.route("/register",methods=["GET","POST"])
def settingData():
FullName = request.form['fullname']
Age = int(request.form['age'])
try:
Gender = request.form['Option']
except Exception as ex:
return render_template("Register.html",n = "Gender not selected")
UserName = request.form['username']
Email = request.form['email']
Pass1 = request.form['password']
Pass2 = request.form['password0']
if Age < 13 or Age > 110:
return render_template("Register.html",n = "Age not corresspond")
if Email == "" or FullName == "" or Age == "":
return render_template("Register.html", n = "Not completed spaces!")
if Pass1 != Pass2:
return render_template("Register.html",n = list_of_errors[3])
if len(Pass1) < 6:
return render_template("Register.html",n = "A password have atleast 6 characters")
freespace = validate_existence(UserName)
if freespace == 1:
return render_template("Register.html",n = "User already exist!")
create_NewUser(UserName,FullName,Age,Pass1,Email,"","","","","")
return render_template("after.html",n = "succes")
#app.route("/login")
def login():
return render_template("py.html")
#app.route('/login',methods=["GET","POST"])
def getingData():
UserName = request.form['username']
Password = request.form['password']
step = validate(UserName,Password)
if Password == "":
return render_template('py.html', n=list_of_errors[2])
if UserName == "":
return render_template('py.html', n = list_of_errors[1])
if step == 0:
return render_template('py.html',n=list_of_errors[0])
return render_template('after.html',n = 'Succes')
if (__name__ == "__main__"):
app.run(debug=True)
when i used "/reg" my flask app dosen't work
this is the html used:
<div class="loginbox">
<img src="{{url_for('static',filename = 'Logo_Appelle.png')}}" class="avatar">
<h1>Create an account</h1>
<h1>{{n}}</h1>
<form name="APPelle" action="." method="POST">
<div class="row">
<div class="column" style="background-color:#060517;">
<p>Full Name</p>
<input type="text" name="fullname" placeholder="Enter Full Name"><br><br>
<p>Age</p>
<input type="text" name="age" placeholder="Enter Age"><br><br>
<p>Gender</p>
<input type="radio" name="Option" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" name="Option" id="female" name="gender" value="female">
<label for="female">Female</label><br><br>
<button class="button">Register</button>
</div>
<div class="column" style="background-color:#03050d;">
<p>Username</p>
<input type="text" name="username" placeholder="Enter Username"><br><br>
<p>Email</p>
<input type="text" name="email" placeholder="Enter Email"><br><br>
<p>Password</p>
<input type="password" name="password" placeholder="Enter Password">
<input type="password" name="password0" placeholder="Confirm Password"><br><br>
</div>
</div>
</form>
</div>
</form>
</body>
</head>
</html
Remove the routes without Methods(POST and get) declared it's conflicting paths.
And method name should be same as the route path
#app.route("/login")
def login():
return render_template("py.html")
#app.route('/login',methods=["GET","POST"])
def getingData():
UserName = request.form['username']
Password = request.form['password']
step = validate(UserName,Password)
if Password == "":
....
....
should be
#app.route('/login',methods=["GET","POST"])
def login():
UserName = request.form['username']
Password = request.form['password']
step = validate(UserName,Password)
if Password == "":
...
...
Related
I'm working with Flask. I have one route and I want to redirect it to other route when pressing a button, but I want to pass an argument. This is my route:
#app.route('/actualize_product.html', methods=['GET', 'POST'])
def actualize_product():
if request.method == 'POST':
print("post")
query1 = """
SELECT id FROM BD.producto
WHERE id=""" + str(request.form['product_id'])
conection = connect()
resultt = conection.execute(query1)[0]
print(resultt)
return redirect(url_for('/edit_product.html', resultado = resultt)) #Line where I'm redirecting
query = "SELECT * FROM BD.Producto ALLOW FILTERING; "
conection = connect()
result = conection.execute(query)
return render_template('actualize_product.html', products = result)
And this is the route I want it to be redirected
#app.route('/edit_product.html', methods=['GET', 'POST'])
def edit_product():
print("edit")
if request.method == 'POST':
print("Im already here")
return render_template('edit_product.html')
The problem is that the edit_product.html is a file where I use jinja2
<h2>Id del producto: {{resultado.id}} </h2> <br>
<form action="app.py" method="get" onsubmit="return formEsValido()">
<input type= "hidden" value = "{{resultado.id}}" id = "id" name = "id">
<label for="product_name"> Nuevo nombre del Producto: </label>
<input type="text" name="product_name" id="product_name" class="form-control">
<label for="product_price"> Nuevo precio del Producto: </label>
<input type="text" name="product_price" id="product_price" class="form-control">
<label for="descripction"> Nueva descripcion del Producto: </label>
<input type="text" name="description" id="description" class="form-control">
<label for="stock">Nuevo stock del Producto</label>
<input type="text" name="stock" id="stock" class="form-control">
<br>
<button class="btn btn-primary"id="index-buttons" type="submit">Editar Producto</button>
</form>
</div>
If I use render_template instead of redirect, it won't work because after clicking on that button, the route will be /actualize_product.html and I want it to change to /edit_product.html' because I have a form there, I don't know how to pass that variable called "resultado" to jinja2 using redirect.
If all you need is the id, you can pass it as an url parameter.
#app.route('/actualize')
def actualize():
return redirect(url_for('edit', id=123))
#app.route('/edit')
def edit():
id = request.args.get('id')
return render_template('edit.html', id=id)
I have two forms:
auth.html
<form class="form-signin pt-5" action="/auth/" method="post" >
{% if error_msg: %}
{{ error_msg }}
{% endif %}
<div class="mt-5 form-label-group">
<p class="text-muted">email</p>
<input type="email" id="inputEmail" class="form-control" name = "email" required autofocus>
</div>
<div class="form-label-group">
<p class="text-muted"> password</p>
<input type="password" id="inputPassword" name="password" class="form-control" required>
<label for="inputPassword"></label>
</div>
<div class="checkbox mb-3"></div>
<button class="btn btn-lg btn-danger btn-block" type="submit">Enter</button>
</form>
success form.html
Success
code in flask is:
app = Flask(__name__)
app.secret_key = "randomstring"
app.config["SECRET_KEY"] = "secret_key"
app.config["EMAIL"] = "test#test.ru"
app.config["PASSWORD"] = "test"
#app.route("/auth/", methods=["GET", "POST"])
def auth_open():
error_msg = "" # Пока ошибок нет
if request.method == "POST":
email = request.form.get("username")
password = request.form.get("password")
if ((email and password) and email == app.config["EMAIL"] and password == app.config["PASSWORD"]):
session["is_auth"] = True
return render_template("/")
else:
error_msg = "Error login or password"
return render_template("auth.html", error_msg=error_msg)
When I input password and login it shows me error message instead of success form.How should I solve this problem?
email = request.form.get("email")
I am new to django and have not found a question corresponding to my entry level. And I just can't figure out how to work with sessions. I want to make a checkbox on login to remember me. After I registered in settings SESSION_EXPIRE_AT_BROWSER_CLOSE = True, you need to enter your username and password after closing the browser. How do I change this parameter using the "remember me" checkbox? Thank you
views.py
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect('/')
else:
messages.info(request, 'invalid credentials')
return redirect('login')
else:
return render(request, 'prof/login.html')
login.html
<body>
<div class="text-center mt-5">
<form style="max-width: 480px; margin: auto" method="post">
{% csrf_token %}
<img
src="https://logodix.com/logo/1713894.jpg"
alt=""
width="120"
height="90"
class="d-inline-block mt-4 mb-4"
/>
<p class="hint-text mb-3">Please sign in</p>
<label class="sr-only" for="username"></label>
<input
type="login"
name="username"
class="form-control"
placeholder="username"
required
autofocus
/>
<label for="password" class="sr-only"></label>
<input
type="password"
name="password"
class="form-control mt-2"
placeholder="password"
/>
<div class="checkbox">
<label for="checkbox">
<input type="checkbox" name="checkbox" value="remember-me" /> remember
me
</label>
</div>
<div class="d-grid gap-2 mt-4">
<input type="Submit" class="btn btn-primary" value="sign in" />
</div>
</form>
<div class="messages">
{% for message in messages %}
<h3>{{message}}</h3>
{% endfor %}
</div>
https://docs.djangoproject.com/en/3.1/topics/http/sessions/#browser-length-sessions-vs-persistent-sessions
you need to set request.session.set_expiry(value) when a user logs on and the checkbox is clicked.
the value in this function is filled out using the following datatypes and values: https://docs.djangoproject.com/en/3.1/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.set_expiry
for you this will mean the following:
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
if request.cleaned_data['remember_me'] == True:
request.session.set_expiry(value)
# ^^^^^^
# insert something here
return redirect('/')
else:
messages.info(request, 'invalid credentials')
return redirect('login')
else:
return render(request, 'prof/login.html')
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
try:
remember = request.POST['remember_me']
if remember:
settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False
except:
is_private = False
settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True
if user is not None:
auth.login(request, user)
return redirect('/')
else:
messages.info(request, 'invalid credentials')
return redirect('login')
else:
return render(request, 'prof/login.html')
I'm trying to signup user but getting some weird error.
please help me to solve it
This is my view file with the function named signup
def signup(request):
if request.method=='POST':
username = request.POST['username']
email = request.POST['email']
password1 = request.POST['password1']
password11 = request.POST['password11']
if password1==password11:
if User.objects.filter(username=username).exists():
messages.info(request,'Username Taken')
return redirect('/account')
elif User.objects.filter(email=email).exists():
messages.info(request,'Email Taken')
return redirect('/account')
else:
user=User.objects.create_user(username=username, password=password1, email=email)
user.save();
auth.login(request,user)
print('user created')
else:
messages.info(request,'Password not Matching')
return redirect('/account')
return redirect('/')
else:
return render(request,'account.html')
And this is my signup file. I've save file with the name account.html.
<form id="regform" style="margin-top: -40px;" action="/signup/" method="post">
{% csrf_token %}
<input type="text" placeholder="Username" name="username">
<input type="email" placeholder="Email" name="email">
<input type="password" placeholder="Password" name="password1">
<input type="password" placeholder="Confirm Password" name="Password11">
<button type="submit" id="btn2">Register</button>
<div>
{% for message in messages %}
<h6>{{message}}</h6>
{% endfor %}
</div>
</form>
Python Side Routing
#app.route("/loginC", methods=["POST"])
def loginPage():
valid = request.form["idnumber"]
if valid is not None: #Creating A New User
username = request.form["username"]
password = request.form["password"]
firstname = request.form["firstname"]
lastname = request.form["lastname"]
idnumber = request.form["idnumber"]
logins["'"+username+"'"] = {"password":"'"+ password +"'", "firstname":"'"+ firstname +"'", "lastname":"'"+ lastname +"'", "idnumber":"'"+ idnumber +"'"}
session["currentUser"] = username
isLogin = True
return redirect("/login")
else:
username = request.form["username"]
password = request.form["password"]
for account in logins:
if username == logins:
if logins["'"+username+"'"]["password"] == password:
session["currentUser"] = username
isLogin = True
return redirect("/login")
return redirect("/login")
Html
<form action="/loginC" class="formLogin" method="post">
<h3>Existing User</h3>
Username: <input type="text" name="username" placeholder="username" required><br>
Password: <input type="password" name="password" placeholder="password" required><br>
<input type="submit" value="Login">
</form>
<br>
<hr class="formLogin">
<br>
<form action="/loginC" class="formLogin" method="post">
<h3>New User</h3>
Username: <input type="text" name="username" placeholder="username" required><br>
Password: <input type="password" name="password" placeholder="password" required> <br>
Firstname: <input type="text" name="firstname" placeholder="firstname" required><br>
Lastname: <input type="text" name="lastname" placeholder="lastname" required><br>
Student ID: <input name="idnumber" type="text" placeholder="ID number" required><br>
<input type="submit" value="Create">
</form>
I keep getting the error:
"werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'idnumber'"
it is requesting the form in the second for bracket aka the 'new user' bracket
In place of :
valid = request.form["idnumber"]
Change to :
If you want to retrieve POST data:
valid = request.form.get("idnumber")
If you want to retrieve GET (query string) data:
valid = request.args.get("idnumber")
Also :
Change method to
#app.route("/loginC", methods=["GET", "POST"])