HTML form with post method sent get request - html

I had a form which used post method. However, after I clicked sumbmit, only get request was sent. Can I please know why?
<form action="/review_page/{{yelp_id}}" method=post>
<label for="review-score">Your overall rating of this restaurant</label>
<select name="score" id="review-score">
{% for num in range(1,6) %}
<option value="{{ num }}">{{ num }}</option>
{% endfor %}
</select>
<div>
<label for="review-title">Title of your review</label><br>
<input type="text" name="title" id="review-title">
</div>
<div>
<label for="reviewText">Your review</label>
<div>
<textarea name="review" id="reviewText" data-minlen="100" data-maxlen="20000"
placeholder="Tell people about your experience"></textarea>
</div>
</div>
<input type="submit" value="Submit Your Review">
</form>
Please also find my routes below.
#app.route("/review_page/<yelp_id>", methods=["POST"])
def save_user_review(yelp_id):
"""Save user review into database"""
user_id = session.get("user_id")
print(user_id)
if user_id is None:
flash("Please log in to leave a review")
return redirect(f"/review_page/{yelp_id}")
else:
user = User.query.get(session["user_id"])
title = request.form.get("title")
score = int(request.form.get("score"))
review = request.form.get("review")
yelp_id = yelp_id
rating = crud.create_rating_without_pic(user, title, score, review, yelp_id)
db.session.add(rating)
db.session.commit()
return redirect(f"/rest_details/{yelp_id}")

Maybe is it.
You have this
<form action="/review_page/{{yelp_id}}" method=post>
And probably you should have this
<form action="/review_page/{{yelp_id}}" method="post">

Related

How to pass data from html to django view to use in URL?

I'm getting an error while working with django urls. I want to pass the value of Name input field after i hit the submit button.
Let's say I've this html form-
<form method='POST' action="{% url 'submittedform' slug=[firstname] %}">
{% csrf_token %}
<div>
<label for="name">Name</label>
<input type="text" name="firstname" id="name">
</div>
<div>
<label for="email">Email</label>
<input type="email" name="useremail" id="email">
</div>
<div>
<label for=phone>Phone</label>
<input type="text" name="phonenumber" id="phone" maxlength="12" pattern="[0-9]{10}">
</div>
<input type="submit" name="" id="btn" value="Submit">
</form>
Here's my view that handling it-
def submittedform(request, slug):
if request.method == 'POST':
# do something here
return render(request,'myapp/welcome.html')
return render(request,'myapp/welcome.html')
and here's my view that's handling it-
urlpatterns = [
path('index/',views.index ,name='index'),
path('welcome/<slug:slug>/',views.submittedform, name='submittedform')
]
I'm not using django forms. How can i get welcome/name working.
If you want to pass a variable to an URL you need redirect with the value:
from django.shortcuts import redirect
return redirect("/welcome/%s/" % slug)
Change the following line
<!-- Removed the bracket -->
<form method='POST' action="{% url 'submittedform' slug=firstname %}">
<!-- Children tags here -->
</form>
Now the variables are accessible in view like
def submittedform(request, slug):
if request.method == 'POST':
name = request.POST['name']
# and more variables as you need
# do something here
# do redirect here or give some message that their form has been
# submitted for their confirmation
return render(request,'myapp/welcome.html')
return render(request,'myapp/welcome.html')

change value form after press button (django)

I have a form where when I select my option and press the "Select" button I need to update the form with the data of my selected object. My problem is that when I do my static object the {% for%} already marks me an error because it is not a list. I do not know if this is the correct way to do it.
This is running Mysql, django 1.11 and python 2.7.15
views.py
def administrador(request):
alumno = Alumnos.objects.all()
mapa = mapas.objects.all()
competencias = Competencias.objects.all()
context = {
'alumno': alumno,
'mapa': mapa,
'competencias': competencias
}
return render(request, 'competencias_app/competencias.html', context)
def seleccion(request):
alumno = Alumnos.objects.get(pk=request.POST['Nombre'])
context = {'alumno': alumno}
return render(request, 'competencias_app/competencias.html', context)
competencias.html
<form action="/seleccion" method="POST">
{% csrf_token %}
<div>
<select id="carrera" name="Carrera">
<option value="1">TICS</option>
<option value="2">Carrera</option>
<option value="3">Carrera</option>
<option value="4">Carrera</option>
<option value="5">Carrera</option>
</select>
</div>
<div>
<select id="Alumno" name="Nombre">
{% for alumno in alumno %}
<option value="{{alumno.idAlumnos}}">{{alumno.nombre}}</option>
{% endfor %}
<input type="submit" name="Seleccionar">
</select>
</div>
<label for="ID">ID</label>
<input type="input" name="id" disabled value="{{alumno.idAlumnos}}"><br>
<label for="apellidos">Apellidos</label>
<input type="input" name="apellidos" disabled value="{{alumno.apellidos}}"><br>
<label for="Correo">Correo</label>
<input type="input" name="Correo" disabled value="{{alumno.correo}}"><br>
</form>
the output when press "seleccionar" is
Request Method: POST
Request URL: http://localhost:8000/seleccion
Django Version: 1.11.21
Exception Type: TypeError
Exception Value:
'Alumnos' object is not iterable
Images for more details
I solve my problem with one if, i don't know if is the correct solution but works!
competencias.html
<form action="/seleccion" method="POST">
{% csrf_token %}
<div>
<select id="carrera" name="Carrera">
<option value="1">TICS</option>
<option value="2">Carrera</option>
<option value="3">Carrera</option>
<option value="4">Carrera</option>
<option value="5">Carrera</option>
</select>
</div>
<div>
<select id="Alumno" name="Nombre">
{% if alumno|length > 1 %}
{% for alumno in alumno %}
<option value="{{alumno.idAlumnos}}">{{alumno.nombre}}</option>
{% endfor %}
{% else %}
<option value="{{alumno.idAlumnos}}">{{alumno.nombre}}</option>
{%endif%}
<input type="submit" name="Seleccionar">
</select>
</div>
<label for="ID">ID</label>
<input type="input" name="id" disabled value="{{alumno.idAlumnos}}"><br>
<label for="apellidos">Apellidos</label>
<input type="input" name="apellidos" disabled value="{{alumno.apellidos}}"><br>
<label for="Correo">Correo</label>
<input type="input" name="Correo" disabled value="{{alumno.correo}}"><br>
</form>
views.py
def administrador(request):
alumno = Alumnos.objects.all()
mapa = mapas.objects.all()
context = {
'alumno': alumno
}
return render(request, 'competencias_app/competencias.html', context)
def seleccion(request):
lstCompetencias = []
alumno = Alumnos.objects.get(pk=request.POST['Nombre'])
for p in Competencias.objects.raw('Select * from test_app_competencias where idmapasfk_id = %s', [request.POST['Nombre']]):
lstCompetencias.append(p)
context = {
'alumno' : alumno,
'competencias' : lstCompetencias
}
return render(request, 'competencias_app/competencias.html', context)

flask multiple submit button

I am using flask and jinja2 to create a simple web app to serve up a simple sklearn algorithm for predictions.
In my html I need to get 4 variables: client id, textid, textid1, textid2
It currently works when I have it all connected to one submit button. But I would like to have two submit buttons to have the client id submit at the top of the page and the textid stuff at the bottom of the page. When I try to have two submit buttons it causes the page to refresh and I not able to connect the client id to the 3 textid vars.
<div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>
<form method="POST">
<input name="text", id='text', placeholder="Client ID #", value="{{ client_id|round|int }}" >
<br>
<label>Enter 3 suggestions</label>
<br>
<input name="textid", placeholder="Suggested Model ID #", value="{{ request.form['textid'] }}"/>
<input name="textid1", placeholder="Suggested Model ID #", value="{{ request.form['textid1'] }}"/>
<input name="textid2", placeholder="Suggested Model ID #", value="{{ request.form['textid2'] }}"/>
<input type="submit" >
</form>
</div>
I'm simply grabbing it in flask like this:
#app.route('/suggestion', methods=['GET', 'POST'])
def with_suggestions():
try:
client_id=request.form['text']
except:
#custom function when client id is not entered to get random one
client_id = recommender.random_client_id()
try:
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
#other functional code after this
How can I break up the html to get two submit buttons? Thanks!!
Now that you have updated your code, all you need to do is add hidden inputs to identify where the click was originated from. Also Remove the leading slash from your url_for like I did below
<div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>
<form method="POST" action={{url_for('suggestion')}}>
<input name="text", id='text', placeholder="Client ID" >
<input type="hidden" name="btn_identifier" value="client_id_identifier" />
<input type="submit" >
</form>
<form method="POST" action={{url_for('suggestion')}}>
<input name="textid", id='text', placeholder="Textid1">
<input name="textid1", id='text', placeholder="textid2 ">
<input name="textid2", id='text', placeholder="Textid3">
<input type="hidden" name="btn_identifier" value="text_id_identifier" />
<input type="submit" value="Submit">
</form>
main.py
from flask import Flask
from flask import render_template, url_for, request, redirect
app = Flask(__name__)
#app.route('/suggestion', methods=['GET', 'POST'])
def with_suggestions():
if request.methods == 'POST':
if request.form['btn_identifier'] == 'client_id_btn':
try:
client_id=request.form['text']
except:
# I think this would go in the second elif statement
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
elif request.form['btn_identifer'] == 'text_id_btn':
# run some code to handle a click that was originated from the second button
return render_template('index.html')
if __name__ == '__main__':
app.run()
I made some changes to your code.
index.html
<div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>
<form method="POST" action={{url_for('suggestion')}}>
<input name="text", id='text', placeholder="Client ID" >
<input type="submit" >
</form>
<form method="POST" action={{url_for('suggestion')}}>
<input name="textid", id='text', placeholder="Textid1">
<input name="textid1", id='text', placeholder="textid2 ">
<input name="textid2", id='text', placeholder="Textid3">
<input type="submit" value="Submit">
</form>
</div>
main.py
from flask import Flask
from flask import render_template, url_for, request, redirect
app = Flask(__name__)
#app.route('/suggestion', methods=['GET', 'POST'])
def suggestion():
if request.method == 'POST':
try:
client_id=request.form['text']
except:
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
return render_template('index.html')
if __name__ == '__main__':
app.run()
Note: Values are store in the variable, print to see
I have simplified the process of fetching the info from multiple buttons. Do note that you require the python flask framework for the "request" method.
home.html
<div class="container mt-5">
<div class="row col-4">
<form method="POST" class="form-register">
<input type="submit" name="submit_button" value="Add Email">
<input type="submit" name="submit_button" value="Clear Recipients">
</form>
</div>
</div>
run.py
if request.method == 'POST':
if request.form['submit_button'] == 'Add Email':
print("add email")
elif request.form['submit_button'] == 'Clear Recipients':
print("clear recipients")
you may refer to the link provided for more example
https://www.codegrepper.com/code-examples/python/checking+if+button+pressed+flask

How to use POST in Django

I use Django 1.11.3 and python2.7
I want write a easy message board
and here is my code
<form name='my form' action='/talkpost/' method='POST'>
{% csrf_token %}
{% for m in moods %}
<input type='radio' name='mood' value='{{ m.status }}'>{{ m.status }}
{% endfor %}
<textarea name='user_post' rows=3 cols=70></textarea><br/>
<label for='user_id'>nicknameļ¼š</label>
<input id='user_id' type='text' name='user_id'>
<label for='user_pass'>password</label>
<input id='user_pass' type='password' name='user_pass'><br/>
<input type='submit' value='submit'>
<input type='reset' value='reset'>
<input type="hidden" name="ok" value="yes">
</form>
urls.py
url(r'^talkpost/', talkpost),
url(r'^talk/', talk),
talk is just for user to see the from and talkpost is for Django to get the post
request
views.py
def talk(request):
template = get_template('talk.html')
moods = Mood.objects.all()
message = 'Leave some message!'
html = template.render(locals())
return HttpResponse(html)
def talkpost(request):
template = get_template('talk.html')
if 'ok' in request.POST:
user_id = request.POST['user_id']
user_pass = request.POST['user_pass']
user_post = request.POST['user_post']
user_mood = request.POST['mood']
message = 'success!'
request_context = RequestContext(request)
request_context.push(locals())
html = template.render(request_context)
return HttpResponse(html)
I try using {% csrf_token %} and RequestContext But i still get CSRF token missing or incorrect.
I have no idea how to fix it
add the following:
from django.views.decorators.csrf import csrf_protect
your function will be:
#csrf_protect
def talkpost(request):
template = get_template('talk.html')
if 'ok' in request.POST:
user_id = request.POST['user_id']
user_pass = request.POST['user_pass']
user_post = request.POST['user_post']
user_mood = request.POST['mood']
message = 'success!'
request_context = RequestContext(request)
request_context.push(locals())
html = template.render(request_context)
return HttpResponse(html)
more info here:
https://docs.djangoproject.com/ko/1.11/ref/csrf/#how-to-use-it

How to Submit Multiple Values in a single HTML Form?

So I have a HTML form:
<html>
<body>
<script>history.pushState('', '', '/')</script>
<form action="http://myserver.com" method="POST">
<input type="hidden" name="Id" value="83" />
<input type="hidden" name="url" value="http://example.com/" />
<input type="submit" value="Submit request" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
As you can see this is submitting the action for <input type="hidden" name="Id" value="83" /> meaning it's submitted for the attribute associated with ID number 83, I'm wanting the action to be submitted for multiple ID values, i.e. 1 - 100. Is this possible? If so how can it be done?
I assume you want to do something like this
<html>
<body>
<script>history.pushState('', '', '/')</script>
<form action="http://myserver.com" method="POST">
<input type="hidden" name="Id[]" value="83" />
<input type="hidden" name="Id[]" value="85" />
<!-- you can add as many as input here for id if you want -->
<input type="hidden" name="url" value="http://example.com/" />
<input type="submit" value="Submit request" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
After this form is posted, on the server side you can get $_POST['id'] as an array and playing around with it.
Add [] to input name:
<input type="hidden" name="ID[1]" value="83" />
<input type="hidden" name="ID[100]" value="100" />
then the in php
print_r($_POST['ID']); //print out the data array
Or use just one input with comma separated values?
<input type="hidden" name=Id value="1, 2, 3,.., 100" />
PHP:
$ids = explode(" ", $_POST['ID']);
Old post, but like to add a Flask solution.
Flask can handle 'name' tags inside the form fields.
<div class="modal-body">
<p>Do you want to add {{ jar.jar_name }} Jar to Map</p>
<div class="col">
<form action="{{ url_for('hornet._jar_on_map')}}">
<input type="hidden" value="{{jar.jar_name}}" name="jar_name"/>
<select class="form-select form-select-lg mb-3" aria-label=".form-select-lg" name="map_name">
{% for map in maps %}
<option value='{{map.map_name}}'>{{ map.map_name }}</option>
{% endfor %}
</select>
<button type="submit" class="btn btn-secondary">Yes</button>
</form>
</div>
The submit button returns to a Flask route '_jar_on_map'. This calls a function to add an item on a map. It is the request.args that shall read your name tags of the different values. Then you can handle those tags inside your function. I made a dict again.
#hornet_bp.route("/add_jar_on_map", methods=["POST", "GET"])
def _jar_on_map():
returneddata = {}
print(request.args)
returneddata["jar_name"] = request.args.get('jar_name')
returneddata["map_name"] = request.args.get('map_name')
print(f"-------------------{returneddata['jar_name']}")
print(f"-------------------{returneddata['map_name']}")
jar = Hornet.find_one_by_name(jar_name=returneddata["jar_name"])
if jar:
update = Hornet.bind_to_map(bind_jar_to_map=returneddata)
if update:
flash(f"Adding Map {returneddata['map_name']} for item {returneddata['jar_name']} OK")
else:
flash(f"Adding Map {returneddata['map_name']} for item {returneddata['jar_name']} FAILED - Does it exist?")
return redirect(url_for(".table_jars"))
By doing document.forms[0].submit(); you are submitting all the input values in that form and values will be saved as Id=83&url=http://example.com/
If you want to submit several forms then you could use a for loop
x = document.forms.length //your desired number or number of forms
for(i = 0; i<x; i++){
document.forms[i].submit();
}