How to fix "Method not allowed" error in Python Flask app - python

I have a defined route in my Python Flask app(which worked fine).
#app.route('/insertpage', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
companyname = request.form['companyname']
username = request.form['username']
userpass = request.form['password']
new_company= Grocery(companyname=companyname,
username=username, userpass=userpass)
try:
db.session.add(new_company)
db.session.commit()
return render_template('index.html', data=Todos.query.all())
except:
return "The problem occurred while adding a new company...."
else:
groceries = Grocery.query.order_by(Grocery.created_at).all()
return render_template('index.html', groceries=groceries)
And I am collecting information in my HTML page:
<form action="/" method="POST">
<div class="form-row">
<div class="col-sm-3 my-1">
<label for="newStuff" class="sr-only">New company:</label>
<input type="text" class="form-control" name="companyname" id="newStuff" placeholder="Enter name of new company">
</div>
<div class="col-sm-3 my-1">
<label for="newStuff" class="sr-only">New username:</label>
<input type="text" class="form-control" name="username" id="newStuff" placeholder="Enter username...">
</div>
<div class="col-sm-3 my-1">
<label for="newStuff" class="sr-only">New password:</label>
<input type="text" class="form-control" name="password" id="newStuff" placeholder="Enter password...">
</div>
<div class="col-sm-3 my-1">
<button type="submit" class="btn btn-primary btn-block">Add</button>
</div>
</div>
</form>
After a couple of successful CRUD operations, I am facing the following error(even if I defined 'POST' and 'GET' in my def).
Method Not Allowed
The method is not allowed for the requested URL.

The action attribute of your HTML form needs to match the name of your Flask route.
Your page is sending a POST to url '/' , so it isn't hitting your route, which is for the path '/insertpage'
You should change it to <form action="/insertpage" method="POST">

Related

Django doesn't redirect to the same page

I'm working on a django project website. When submitting a form I need to save the data and show a message with from django.contrib import messagesmodule. It works perfectly with saving data but it never shows the message and redirecting to the same page.
Views.py class.
def showIndex(request):
if request.method == 'POST':
contact = Contact()
name = request.POST.get('name')
email = request.POST.get('email')
message = request.POST.get('message')
contact.name = name
contact.email = email
contact.message = message
print('yes and no ')
messages.success(request, 'Profile details updated.')
contact.save()
return render(request,'index.html')
return render(request,'index.html')
and this is the codes in index.html. I have created the form here.
<form method="POST" class="u-clearfix u-form-spacing-30 u-form-vertical u-inner-form" style="padding: 10px">
{% csrf_token %}
<div class="u-form-email u-form-group u-form-partition-factor-2">
<label for="email-319a" class="u-label u-text-body-alt-color u-label-1">Email</label>
<input type="email" placeholder="Enter a valid email address" id="email-319a" name="email" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required="" />
</div>
<div class="u-form-group u-form-name u-form-partition-factor-2">
<label for="name-319a" class="u-label u-text-body-alt-color u-label-2">Name</label>
<input type="text" placeholder="Enter your Name" id="name-319a" name="name" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required="" />
</div>
<div class="u-form-group u-form-message">
<label for="message-319a" class="u-label u-text-body-alt-color u-label-3">Message</label>
<textarea placeholder="Enter your message" rows="4" cols="50" id="message-319a" name="message" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required=""></textarea>
</div>
<div class="u-align-left u-form-group u-form-submit">
Submit
<input type="submit" value="submit" class="u-form-control-hidden" />
</div>
</form>
<div>
{%for message in messages%}
{{message}}
{%endfor%}
</div>
You have to pass the messages variable to the render method:
render(request,'index.html', {'messages': messages})

Flask does not direct to the home page

I'm am using flask and trying to access my homepage after the login and when trying to click on the log in button, the endpoint for the home is not getting called.
Below is my app.py file.
from flask import Flask, request, jsonify, render_template, redirect, url_for
from tensorflow import keras
app = Flask(__name__, template_folder='templates')
#app.route('/')
def home():
print('success1')
return render_template(r'index.html')
#app.route('/success')
def success():
# return 'logged in successfully'
print('success')
render_template(r'Home.html')
if __name__ == "__main__":
app.run()
Below is my index.html code. (login form) Only the tag is added below.
<form id = "login-form" action="" method="post">
<div class="form-group">
<input type="text" class="form-control" name="username" id="username" placeholder="Username">
</div>
<br>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
<br>
<div class="d-grid">
<button type="button" class="btn btn-primary btn-block" id="login-form-submit">Sign In</button>
</div>
</form>
Below is the validation.js file I have created.
const loginForm = document.getElementById("login-form");
const loginButton = document.getElementById("login-form-submit");
const loginErrorMsg = document.getElementById("login-error-msg");
loginButton.addEventListener("click", (e) => {
e.preventDefault();
const username = loginForm.username.value;
const password = loginForm.password.value;
if (username === "user" && password === "user123") {
alert("You have successfully logged in.");
window.location.replace("{{ url_for('success') }}");
} else {
loginErrorMsg.style.opacity = 1;
}
})
When I click on the sigh in button, I do get the alert saying 'you have successfully logged in' but I'm not getting redirected to the home.html. I suspect that something is wrong in the way that I call the endpoint in my javascript file.
Kindly help me with this.
I can't help you with the Javascript validation but the below python and html code works for me:
#app.route('/success', methods=['POST'])
def success():
if request.method == 'POST':
return render_template(r'home.html')
<form id = "login-form" action="{{ url_for('success') }}" method="post">
<div class="form-group">
<input type="text" class="form-control" name="username" id="username" placeholder="Username">
</div>
<br>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
<br>
<div class="d-grid">
<button type="submit" class="btn btn-primary btn-block" id="login-form-submit">Sign In</button>
</div>
</form>
I hope this helps!

can't get the POST parameters in django

I am trying to make a login-page using django, I am facing troubles in getting POST parameters
login view:
def ProcLogin(request):
if request.method == 'POST':
account_name = request.POST.get('username','')
password = ToMd5(request.POST.get('password',''))
if not account_name or not password: return HttpResponse("invalid input")
template code:
<form method="post" action="{% url 'Main:login' %}" class="login_form">
{% csrf_token %}
<div class="form-group text-right">
<label for="username">User name:</label>
<input id="username" type="text" class="form-control box_shadow">
</div>
<div class="form-group text-right">
<label for="password">Password: </label>
<input id="password" type="password" class="form-control box_shadow">
</div>
<button type="submit" class="login_btn"></button>
</form>
Output when testing it:
invalid input
everything is supposed to be correct except the results aren't. Thank you.

Bad Request on POST form request with Flask [duplicate]

This question already has answers here:
Post values from an HTML form and access them in a Flask view
(2 answers)
Closed 4 years ago.
I'm using flask to make a login system and when I POST the form from the HTML form and I keep getting the following error: werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'username'.
I've looked up the error on Google and have gotten nowhere.
My HTML code is this:
<div class="card rounded-0" id="register_form">
<div class="card-header">
<h3 class="mb-0">Register</h3>
</div>
<div class="card-body">
<form class="form" role="form" method="POST" action="/auth/register" id="form">
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control form-control-lg rounded-0" id="email" required="">
<div class="invalid-feedback">Enter your Email.</div>
</div>
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control form-control-lg rounded-0" id="username" required="">
<div class="invalid-feedback">Enter your Username.</div>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control form-control-lg rounded-0" id="password" required="">
<div class="invalid-feedback">Enter your Password.</div>
</div>
<button type="submit" class="btn btn-success btn-lg float-right" id="btnLogin_regi">Register</button>
</form>
<p>Already have an account? </p><a class="btn btn-primary btn-lg" tabindex="-1" role="button" id="login_btn">Login</a>
</div>
</div>
My Python code is this:
#app.route('/auth/register', methods=["POST"])
def auth_post():
if request.method == "POST":
try:
q = database.query(User).filter(User.username == request.form.get("username"))
exists = database.query(q.exists()).scalar()
if exists:
return render_template("auth.html", error="User with same username/email exists.")
else:
username = str(request.form["username"])
password = str(request.form["password"])
email = str(request.form["email"])
print("Username: "+username+", Password: "+password+", Email: "+email)
temp = User(username=username, password=password, email=email)
database.add(temp)
database.commit()
except sqlalchemy.orm.exc.MultipleResultsFound:
return "Well this shouldn't be happening but it is. Join our Discord Server and tell one of the devs that the following error occured:\n<code>sqlalchemy.orm.exc.MultipleResultsFound (register)</code>"
I expect it to push the data to the SQLite Database, and once it does that, I will add more features after that.
The issue was that I didn't add name= to the input field.
Thanks #SuperShoot.

Data not appearing in database after form submission

I have created an HTML form trying to do simple registration.
The problem is that after clicking submit button no error appears but when I chech database the data from fields is not there.
signup.html
<form action="\polls\Registration" method="POST">
<div class="form-group mb15">
<input type="text" class="form-control" name="userName" placeholder="Enter Your Username" required>
</div>
<div class="form-group mb15">
<input type="password" class="form-control" name="password" placeholder="Enter Your Password">
</div>
<div class="form-group mb15">
<input type="text" class="form-control" name="fullName" placeholder="Enter Your Full Name">
</div>
<div class="form-group mb20">
<label class="ckbox">
<input type="checkbox" name="checkbox">
<span>Accept terms and conditions</span>
</label>
</div>
<div class="form-group">
<button class="btn btn-success btn-quirk btn-block">Create Account</button>
<br>
Already a member? Sign In Now!
</div>
</form>
forms.py
class RegistrationForm(forms.Form):
userName= forms.CharField(label='Username',max_length=100)
password = forms.CharField(label='Password', max_length=100)
fullName= forms.CharField(label='Full Name', max_length=100)
myview.py
def reg(request):
if request.method == 'POST':
the request:
form = forms.RegistrationForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/polls/signin')
else:
form = forms.RegistrationForm()
return render(request, 'signup.html', {'form': form})
urls.py
urlpatterns = [
url(r'^Registration', myview.reg,name='Registration'),
]
[SOLVED]
What I did is that I created a model to handle form processing.I also used modelForm instead of forms. For anyone having same issue check this

Categories

Resources