Flask cannot see form - python

I'm trying to build a simple application using Leaflet in Flask, but I have a problem with the form. I want to send data from the form to my database but when I use the POST method, Flask doesn't want to read this method. When I used only GET, all values were empty in the database. When i used POST and GET nothing happened, none of the rows were added to the database.
forms.py
class EventForm(FlaskForm):
date_start = DateField(validators=[DataRequired()])
date_end = DateField(validators=[DataRequired()])
type = StringField(validators=[DataRequired()])
name = StringField(validators=[DataRequired()])
len_route = FloatField(validators=[DataRequired()])
mapa.html with Leaflet map and the form
<div id="fields">
<form action="" method="post">
<input type="text" id="route_len" class="form-control mb-2" name="route_len_input" placeholder="Długosc trasy">
<br>
<button id="draw-button" class="btn btn-success">Rysuj trase</button>
<br><br>
<input type="text" id="name" class="form-control mb-2" name="name_input" placeholder="Nazwa">
<br>
<input type="datetime-local" id="date_st" class="form-control mb-2" required name="date_st_input" placeholder="Data startu">
<br>
<input type="datetime-local" id="date_end" class="form-control mb-2" required name="date_end_input" placeholder="Data końcowa">
<br>
<select id="type" class="form-control mb-2" name="type_input">
<option></option>
<option value="Bieganie">Bieganie</option>
<option value="Rower">Rower</option>
<option value="Nordic walking">Nordic Walking</option>
</select>
<br>
<button type="submit" id="end-button" name="sub" class="btn btn-danger">Zakończ rysowanie</button>
<br><br>
</form>
</div>
routes.py
#app.route('/mapaa',methods=["GET","POST"])
def mapa():
if request.method == "POST":
data_pocz = request.form['date_st_input']
data_kon = request.form['date_end_input']
nazwa = request.form['name_input']
typ = request.form['type_input']
dlugosc = request.form['route_len_input']
event_database = Event(date_start=data_pocz, date_end=data_kon, type=typ, name=nazwa, len_route=dlugosc)
db.session.add(event_database)
db.session.commit()
return render_template('mapaa.html', title='Mapa')

You should link the form to your flask method
<form method="POST" action="/mapaa"> [...]

Related

Django - pass multiple HTML form inputs into a view

I have 3 form inputs that will be submitted when one master button is clicked to then be passed into a view as the request parameter. I would like to get the values of first_name, last_name and email inside my view using request.get(). When the button is clicked the values inside my form appear as None
HTML:
<div id="form_content">
<form action="" method="post">
<section class="form_inputs">
<label for="first_name">First Name:</label>
<input type="text" id="first_name">
</section>
<section class="form_inputs">
<label for="last_name">Last Name:</label>
<input type="text" id="last_name">
</section>
<section class="form_inputs">
<label for="email">Email:</label>
<input type="text" id="email">
</section>
<input type="submit" value="Submit">
</form>
</div>
views.py
def home(request):
form_response = request.GET.get("form_content")
print(form_response)
context = {"title": "Home"}
return render(request, "myApp/home.html", context)
first you need to add csrf_token in your code for post method and also give a name for each input like this :
<div id="form_content">
<form action="" method="post">
{% csrf_token %}
<section class="form_inputs">
<label for="first_name">First Name:</label>
<input type="text" name="first_name" id="first_name">
</section>
<section class="form_inputs">
<label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="last_name">
</section>
<section class="form_inputs">
<label for="email">Email:</label>
<input type="text" name="email" id="email">
</section>
<input type="submit" value="Submit">
</form>
</div>
and then:
def home(request):
first_name = request.POST['first_name']
last_name = request.POST['last_name']
email = request.POST['email']
print(first_name, last_name, email)
context = {"title": "Home"}
return render(request, "myApp/home.html", context)
In your input tags, you have not passed the name parameter. Pass the name parameter in your input tags, as Django collects the data from the name tags.
For example, in your case, it must be:
<input type="text" id="id_first_name" name="first_name">
<input type="text" id="id_last_name" name="last_name">
<input type="text" id="id_email" name="email">

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

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

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.

How to fill inputs when editing an article in flask

I have a list of articles.
After I press Edit, I am redirected to another page containing in the url the id of the article that wants to be edited.
Edit
This is where I am redirected:
And I want the inputs to be filled with the title and the body text of the respective article.
This is my backend function:
#app.route('/edit_article/<string:id>', methods=['POST', 'GET'])
def edit_article(id):
conn = mysql.connect()
cursor = conn.cursor()
result = cursor.execute("SELECT * from articles where id=%s", [id])
data = cursor.fetchone()
if result < 0:
flash("Article does not exist!")
cursor.close()
conn.close()
return render_template("edit_article.html", data=data)
How can I use data to fill those inputs? Please help. Thank you.
I will put also the edit_article.html
{% extends 'layout.html' %}
{% block body %}
<div class="container">
<div class="jumbotron">
<h1>Bucket List App</h1>
<form class="form-addArticle">
<label for="inputTitle" class="sr-only">Title</label>
<input type="name" name="inputTitle" id="inputTitle" class="form-control" placeholder="Title" required autofocus>
<label for="inputBody" class="sr-only">Body</label>
<input type="text" name="inputBody" id="inputBody" class="form-control" placeholder="Body" required autofocus>
<button id="btnEditArticle" class="btn btn-lg btn-primary" type="button">Update article</button>
</form>
<p class="text-center" style="color:red" id="message"></p>
</div>
</div>
{% endblock %}
You can just need to add value="{{ ... }}" to your inputs:
<input type="name" value="{{ data[0] }}" name="inputTitle" id="inputTitle" class="form-control" placeholder="Title" required autofocus>
<input type="text" value="{{ data[1] }}" name="inputBody" id="inputBody" class="form-control" placeholder="Body" required autofocus>
But it's recommended to name the values:
name, text = cursor.fetchone()
return render_template("edit_article.html", name=name, text=text)
and then
<input type="name" value="{{ name }}" name="inputTitle" id="inputTitle" class="form-control" placeholder="Title" required autofocus>
<input type="text" value="{{ text }}" name="inputBody" id="inputBody" class="form-control" placeholder="Body" required autofocus>
But I'd personally recommend WTForms module instead of rendering forms manually - it can for example help to validate your inputs properly.

Django passing value from template to view

I'm having trouble passing values from my template to view. Basically I created a form for user registration, and want to pass the values from the template to view so that I can construct a User object to add to my database. But somehow my "input" is not working when I add name={{user_form.username}}. Also, I want to pass values 0,1,2 respectively when I select "borrower", "libarrian" and "clerk", what can I do to implement this?
Below are my codes.
<form id="user_form" method="post" action="/sign_up/" class="form-signin" role="form">
{% csrf_token %}
<h2 class="form-signin-heading">Signup </h2>
{% if error%}
<div class="error"> Your registration has been unsuccessfull </div>
{% endif %}
<input type="text" class="form-control" name="username" value="{{user_form.username}}" placeholder="Username" required autofocus>
<input type="password" class="form-control" name="password1" placeholder="Password" value="" required>
<input type="password" class="form-control" name="password2" placeholder="Retype password" value="" required>
<select class="form-control">
<option value="2">Librarian</option>
<option value="0">Borrower</option>
<option value="1">Clerk</option>
</select>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign Up</button>
</form>
In forms.py
class UserForm(forms.Form):
username = forms.CharField(max_length=30)
password1 = forms.CharField(widget=forms.PasswordInput())
password2 = forms.CharField(widget=forms.PasswordInput())
In views.py
def sign_up(request):
registered = False;
error = False;
if request.method == 'POST':
user_form = UserForm(request.POST)
if user_form.is_valid():
registered = True
username = user_form.cleaned_data['username']
password = user_form.cleaned_data['password']
user = User.objects.create_user(username, None, password)
user.save()
else:
error = True;
else:
user_form = UserForm()
return render(request, 'books/sign_up.html',
{'user_form':user_form,
'registered':registered, 'error':error})
Below form should work.
<form id="user_form" method="post" action="/sign_up/" class="form-signin" role="form">
{% csrf_token %}
<h2 class="form-signin-heading">Signup </h2>
<input type="text" class="form-control" name="username" value="{{user_form.username}}" placeholder="Username" required autofocus>
<input type="password" class="form-control" name="password1" placeholder="Password" required>
<input type="password" class="form-control" name="password2" placeholder="Retype password" required>
<select class="form-control">
<option value="1">Librarian</option>
<option value="0">Borrower</option>
<option value="2">Clerk</option>
</select>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign Up</button>
</form>
Changes I have done are -
Change the names of username and password textboxes
Change the type for username textbox
Added value attribute in select control

Categories

Resources