How i can use multiple forms in loop at once - python

I have problem with using multiple forms at once, tried with loop count in name but when i check correct options and then submit I get this error:
The browser (or proxy) sent a request that this server could not understand.
Code:
{%for tournament in tournament_query%}
<div class="body-main">
<div class ="body-select">
<form action="", method="POST">
<input type="radio" name="option" value="{{tournament.player_one}}"> {{tournament.player_one}}<br>
</form>
</div>
<div class ="body-selected">
<form action="", method="POST">
<input type="radio" name="option" value="{{tournament.player_two}}"> {{tournament.player_two}}<br>
</div>
<input type="submit" value="Submit">
</form>
</div>
{%endfor%}
my flask route =
#app.route("/news", methods=['POST', 'GET'])
#login_required
def news():
tournament_query = Walka.query.join(Walka.Tournament).filter_by(name = 'Das').all()
if request.method == "POST":
option = request.form['options']
return option
return render_template("news.html", tournament_query = tournament_query)
I want to get value from every one but I don't know how I can acquire it

Related

django form not posting, but other form on page does?

I have two forms on a page. The first form properly sends a POST request to my view but the second form sends a GET (I need it to also send a POST). I've made this mistake before and this time I made sure that the button is set to "submit", but for some reason it still sends a GET.
form 1 (working as intended):
<form method="POST">
{% csrf_token %}
<div class="row form-row">
<div class="col-sm-6">
<div class="form-group">
<label for="start_date">Start</label>
<input class="form-control" type="text" data-flatpickr data-alt-input="true" data-date-format="Y-m-d" name="start_date" data-enable-time="true">
</div>
<div class="form-group">
<label for="end_date">End</label>
<input class="form-control" type="text" data-flatpickr data-alt-input="true" data-date-format="Y-m-d" name="end_date" data-enable-time="true">
</div>
</div>
</div>
<input type="hidden" name="eventtype" value="availability">
<button class="btn btn-primary" type="submit">Save changes</button>
</form>
form 2 (sends a GET but I want this to POST):
<form method="POST">
{% csrf_token %}
{% if form.errors %}{{form.errors}}{% endif %}
<input type="hidden" name="pk" value="{{ i.id }}">
<input type="hidden" name="eventtype" value="invite">
<button class="btn btn-primary" type="submit">Confirm</button>
</form>
views.py
def createevent(request):
if request.method == 'GET':
<<code>>
else:
try:
eventtype = request.POST.get('eventtype', None)
print(eventtype)
if eventtype == "availability":
form = EventForm(request.POST)
newEvent = form.save(commit=False)
newEvent.mentor_user = request.user
newEvent.requester_user = None
newEvent.notes = None
newEvent.save()
elif eventtype == "invite":
form = EventForm(request.POST)
updatedEvent = form.save(commit=False)
updatedEvent.isConfirmed = True
updatedEvent.save()
return redirect('createevent')
except ValueError:
print(form.errors)
return render(request, 'events/createevent.html', {'form':EventForm(), 'error':'There was an error. Please make sure you entered everything correctly!'})
urls.py
# Events
path('events/create', views.createevent, name='createevent'),
# path('calendar/<slug:slug>', views.viewevent, name='viewevent'),
path('events/<int:pk>/edit', views.updateevent, name='updateevent'),
console output for form 1 and form 2:
"GET /events/create?csrfmiddlewaretoken=<<redacted>>&pk=2&eventtype=invite HTTP/1.1" 200 25560
"POST /events/create?csrfmiddlewaretoken=<<redacted>>&pk=2&eventtype=invite HTTP/1.1" 302 0
Set the action of form to your url path.
Look at this:
<form name="form" method="POST" action="{% url 'your_url_name' %}">
The issue ended up being the form was wrapped in another form tag further up in the template code. When I clicked the Submit button, the Submit button was firing on the first form and not the second. Just a bad copy/paste.

How to get HTML Input using Python Flask

I am planning to get input from an HTML Form when submitted, the input will be send over to Python. Here is the HTML File
<form method="GET">
<div class="form-inline">
<div class="form-group">
<input type="email" class="line-input" name="userEmail" placeholder="Email">
</div>
<div class="form-group">
<input type="password" class="line-input" name="userPassword" placeholder="Password">
</div>
</div>
<div class="form-inline">
<div class="form-group">
<input type="email" class="line-input" name="recipientMail" placeholder="Recipient">
</div>
<div class="form-group">
<input type="email" class="line-input" name="CCEmail" placeholder="CC">
</div>
</div>
<div class=" form-group">
<button type="submit" class="btn btn-light text-primary btn-block" style="margin : 20px 20px -10px 0px">Send Message</button>
</div>
</form>
Now I don't know the best way to do this, I tried this in Python but doesn't seem to work
#app.route('/', methods=['POST'])
def form_post():
userEmail = request.form['userEmail']
userPassword = request.form['userPassword']
return userEmail, userPassword
Can anyone help me out here?
Change your form method from GET to POST, as your route only specifies "POST", and will not accept any other requests of a different type:
<form method="POST">
Edit: if you wish to specify both methods, ensure that your route checks for the correct type of request currently being sent when the route is triggered:
#app.route('/', methods=['POST','GET'])
def form_post():
if flask.request.method == 'POST'
userEmail = request.form['userEmail']
userPassword = request.form['userPassword']
return userEmail, userPassword
return flask.render_template('something.html')
Note, however, that you are creating your form on the home route ('/'). It may be best to return a link to the page that has the form code:
#app.route('/')
def home():
return 'Welcome! login here'
#app.route('/login', methods=['GET', 'POST']):
if flask.request.method == 'POST'
userEmail = request.form['userEmail']
userPassword = request.form['userPassword']
return flask.redirect('/')
return flask.render_template('form_filename.html')

Getting value from select tag using flask

I'm new to Flask and I'm having trouble getting the value from my select tag. I have tried request.form['comp_select'] which returns a Bad Request. However, when I try using request.form.get('comp_select'), my return page returns a blank list "[]".
My html:
<form class="form-inline" action="{{ url_for('test') }}">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Please select</span>
<select name="comp_select" class="selectpicker form-control">
{% for o in data %}
<option value="{{ o.name }}">{{ o.name }}</option>
{% endfor %}
</select>
</div>
<button type="submit" class="btn btn-default">Go</button>
</div>
</form>
My app.py:
#app.route("/test" , methods=['GET', 'POST'])
def test():
select = request.form.get('comp_select')
return(str(select)) # just to see what select is
Sorry in advance if my formatting is off for the post (also new to Stack Overflow).
It's hard to know for certain from what you've provided, but I believe you need to add method="POST" to your <form> element.
From the flask doc for the request object:
To access form data (data transmitted in a POST or PUT request) you can use the form attribute. ... To access parameters submitted in the URL (?key=value) you can use the args attribute.
So, if you submit your forms via POST, use request.form.get(). If you submit your forms via GET, use request.args.get().
This app behaves the way you want it to:
flask_app.py:
#!/usr/bin/env python
from flask import Flask, flash, redirect, render_template, \
request, url_for
app = Flask(__name__)
#app.route('/')
def index():
return render_template(
'index.html',
data=[{'name':'red'}, {'name':'green'}, {'name':'blue'}])
#app.route("/test" , methods=['GET', 'POST'])
def test():
select = request.form.get('comp_select')
return(str(select)) # just to see what select is
if __name__=='__main__':
app.run(debug=True)
templates/index.html
<form class="form-inline" method="POST" action="{{ url_for('test') }}">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Please select</span>
<select name="comp_select" class="selectpicker form-control">
{% for o in data %}
<option value="{{ o.name }}">{{ o.name }}</option>
{% endfor %}
</select>
</div>
<button type="submit" class="btn btn-default">Go</button>
</div>
</form>

Simple django POST not working

I have a form like this:
<form action="{% url "forum.posts" forum=forum.slug thread=thread.slug %}" method="POST">
{% csrf_token %}
<div class="form-group">
<textarea class="form-control" placeholder="Začni tipkati.."></textarea>
</div>
<input type="submit" class="btn btn-success" value="Pošlji odgovor">
</form>
views.py
'''
Display all posts in a thread or create a new post in a thread.
'''
def posts(request, forum, thread):
forum = Forum.objects.get(slug=forum)
thread = Thread.objects.get(slug=thread)
if request.method == "POST":
return HttpResponse('ok')
posts = thread.posts.all()
return render(request, 'forum/posts.html', {
'forum': forum,
'thread': thread,
'posts': posts
})
urls.py (relevant part):
# List all posts in a thread / Submit a post to a forum
url(r'^(?P<forum>[-\w]+)/(?P<thread>[-\w]+)/$', 'forum.views.posts', name='forum.posts'),
HTML output:
<form action="/forum/o-spletiscu/novatemaa/" method="post">
<input type="hidden" name="csrfmiddlewaretoken" value="4PQWDsAfHyjrhUnYU5P9vVhtaY3vLPBU">
<div class="form-group">
<textarea name="post-body" class="form-control" placeholder="Začni tipkati.."></textarea>
</div>
<input type="submit" class="btn btn-success" value="Pošlji odgovor">
</form>
After I hit submit, I expect ok to be returned, instead page refreshes and nothing happens.
Normal GET requests are working though..
What am I missing?
Edit:
It's working when I use #csrf_exempt on posts method.
page refreshes and nothing happens
Problem with your action value. try to inspect it and find wither the url is correct or not.
OR
your form does not have any input with name property.
Try this:
<form action="{% url "forum.posts" forum=forum.slug thread=thread.slug %}" method="POST">
{% csrf_token %}
<div class="form-group">
<textarea class="form-control" placeholder="Začni tipkati.." name="something"></textarea>
</div>
<input type="submit" class="btn btn-success" value="Pošlji odgovor">
</form>

Flask receiving empty forms

I'm trying to get a simple form set up in Flask for my own education. I've got a login.html page with this form code:
<form action="{{ url_for('login') }}" method="post">
<div>
<label for="username">Username</label>
<div>
<input type="text" id="username" name="username" placeholder="Username">
</div>
</div>
<div>
<label for="password">Password</label>
<div>
<input type="password" id="password" name="password" placeholder="Password">
</div>
</div>
<div >
<input class="btn" type="submit">
</div>
</form>
I'm using code like the following to receive it, but Flask returns an empty request.form so I can't process it.
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
request.form['username']
...
I really don't want to learn another library (WTForms) right now, and I'm using bootstrap so that will add to the headache. What am I not seeing here with Flask/HTML?
I had this problem, but it was because I forgot to assign a name attribute to my input elements and I was trying to refer access the form data by the id attribute instead
i.e.
My HTML and Python was as shown below
HTML
<input type="text" id="usernameTxtBx">
Python
request.form['usernameTxtBx']
What I have done now:
HTML
<input type="text" name="username" id="usernameTxtBx">
Python
request.form['username']
I also needed to ensure that I was using a POST request. A GET request gave me an empty dictionary in my python code.
The OP made neither of these mistakes. But this may help someone that stumbles on this thread.
I had that problem.
Some tools like postman or some libraries or web browser sends the data in a way that flask does not identify as posted values. From my point of view this is a flask issue.
This is the workaround I followed to solve it:
1 - I sent the information using json. Have a look to this:
How to send a JSON object using html form data
2 - I instead of getting the parameters using:
value = request.form["myparamname"]
I used this:
json_data = request.get_json(force=True)
value = json_data["myparamname"]
just use request.get_json() in POST requests
login.html
{% extends "layout.html" %}
{% block content %}
<div class="form">
<h2>Sign In</h2>
{% for field in form.errors %}
{% for error in form.errors[field] %}
<div class="alert alert-error">
<strong>Oops...</strong> {{error}}.
</div>
{% endfor %}
{% endfor %}
<form action="{{ url_for('login') }}" method=post>
{{ form.hidden_tag() }}
{{ form.email.label }}
{{ form.email }}
{{ form.password.label }}
{{ form.password }}
<p> <input id="submit" name="submit" type="submit" class="btn btn-inverse" value="Sign In"></p>
</form>
</div>
{% endblock %}
forms.py
class SigninForm(Form):
email = TextField("email", [validators.Required("Please enter your email")])
password = PasswordField('Password', [validators.Required("Please enter a password.")])
submit = SubmitField("Sign In")
Then import the signinform in your views and create your login method like this
#app.route('/login', methods=['GET', 'POST'])
def signin():
form = SigninForm()
if form.validate_on_submit():
session['email'] = form.email.data
flash('You are logged in')
return redirect(url_for('dashboard'))
return render_template('signin.html', form=form)
Refer this tutorial for more detailed instructions
http://pypix.com/python/building-flask-blog-part-1/

Categories