Flask Redirect is Duplicating POST request - python

I'm doing a simple shopping website with a order confirmation page but I'm finding that there are duplicate POST requests to my /confim-order route. I have a home page that redirects on POST:
#views.route('/', methods=['GET', 'POST'])
#login_required
def home():
if request.method == 'POST':
# save information from the form for later use
session['text'] = request.form.get('samples')
session['note'] = request.form.get('note')
return redirect(url_for('views.confirm_order'))
return render_template("home.html", user=current_user)
My order confirmation function:
#views.route('/confirm-order', methods=['GET', 'POST'])
#login_required
def confirm_order():
if request.method == 'POST':
text = session['text']
note = session['note']
session.pop('text', None)
session.pop('note', None)
create_order(current_user, text, note)
return redirect(url_for('views.home'))
elif request.method == 'GET':
text = session['text']
note = session['note']
sample_list = get_samples(text, note)
return render_template("confirm.html", user=current_user, sample_list=sample_list)
There's no JavaScript in the HTML template. What's in confirm.html is essentially:
<form method="POST">
<div class="form-group">
<label for="cc">Credit Card</label>
<input type="text" class="form-control" id="cc" name="cc" placeholder="Credit Card Number" />
</div>
Click button to place order:
<p></p>
<div align="right">
<button type="submit" id="submit_btn" class="btn btn-success">Place Order</button>
</div>
</form>
This is what I see: sometimes, clicking submit works fine. Most times clicking submit results in two POST requests to confirm_order() and then I get a "This site can’t be reached" message in my browser at http://localhost:5000/confirm-order. I've been at this for almost an entire day. I put some print statements that seem to suggest the first POST to /confirm-order is initiated correctly from the template rendered we reach /confirm-order by GET from home: /. The second POST to /confirm-order came immediately after first the POST from within POST of /confirm-order. When that happens, I get the "This site can't be reached" message and I find that duplicate orders have been created.
I've searched online and most people that have duplicate POST issues are using JavaScript along with the form submission button. But my page doesn't use Javascript. If someone sees what's wrong, any help is greatly appreciated. Thank you.
EDIT: Here's the create_order() function in case something in there is causing the problem:
def create_order(user, text, note):
new_order = Order(user_id=current_user.id, text=text,
status='submitted', note=note)
db.session.add(new_order)
db.session.commit()

I'm not 100% sure this is the issue but it's the most likely thing I can think of.
I think there are some issues in your html since you don't specify the url for action. I would also use an input tag rather than button for submit.
More generally, I would also recommend following a few of the things mentioned here. So use the data in request.form rather than in the session object since you can control and validate that more explicitly within Flask (for instance if this is going into production you may want to implement WTF Forms for security reasons to prevent CSRF).
<form action="/confirm-order" method="post">
<div class="form-group">
<label for="po">Purchase Order</label>
<div class="form-group">
<label for="cc">Credit Card</label>
<input type="text" class="form-control" id="cc" name="cc" placeholder="Credit Card Number" />
</div>
Click button to place order:
<p></p>
<div align="right">
<input type="submit" id="submit_btn" class="btn btn-success">Place Order</input>
</div>
</form>

Related

How to move variables from python to template and back?

I'm trying to get information from a form to my python file and then put into a template. Thing is, i know the form is working but i couldn't show it into the template.
Form here:
<div class="container" id="cont1">
<form action="http://127.0.0.1:5000/areas" method="POST" enctype="multipart/form-data">
<label for="author">Autor</label>
<input type="text" id="author" name="author"><br><br>
<label for="intro">Introdução</label>
<input type="text" id="intro" name="intro"><br><br>
<label for="content">Conteúdo</label>
<input type="text" id="content" name="content"><br><br>
<input type="file" id="planilha" name="planilha" accept=".csv"><br><br>
<input type="submit" value="Enviar">
</form>
</div>
then i try to get the data in app.py:
#app.route('/areas', methods=['GET', 'POST'])
def areas():
if request.method == "POST":
#app.context_processor
def f1():
aut = request.form.get['author']
intr = request.form['intro']
cont = request.form['content']
return dict(a=aut, i=intr, c=cont)
return render_template("areas.html")
else:
return render_template("areas.html")
I know it's working because i tried it out of the route and it showed what the form had. Now when i try into the route:
AssertionError
AssertionError: A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.
To fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.
The decorator was the solution i found to get the data so i could place into templates like this:
<text>{{a}}</text>
The error is caused by the incorrect usage of the decorator. You don't need a decorator to pass variables to templates. render_template also accepts arguments which you can directly pass into your HTML file.
The following should work:
#app.route('/areas', methods=['GET', 'POST'])
def areas():
if request.method == "POST":
aut = request.form['author']
intr = request.form['intro']
cont = request.form['content']
return render_template("areas.html", a=aut, i=intr, c=cont)
else:
return render_template("areas.html")

how to delete an object in django [duplicate]

i want to delete a task from the database so i use this code
this is my delete view
def task_Delete(request,id=None):
if request.method == 'POST':
form = TaskForm()
id = int(request.POST.get('task.id'))
task = Task.objects.get(id=id)
task.delete()
messages.success(request,"successfully delete")
return render_to_response('home.html', {'form': form})
and that is my urls.py
url(r'^task_Delete/$', views.task_Delete, name='task_Delete')
this the code of the button delete :
<form action="{% url 'task_Delete' %}" method="post" >
{% csrf_token %}
<input type="hidden" name="task_id" value="{{task.id}}" />
<input type="submit" value="delete task">
</form></td>
</tr>
when i click on delete nothing happend i don't know why , please help thanks in advance
There are various problems in your code (for example the TaskForm is not needed at all) however if you change the line
id = int(request.POST.get('task.id'))
to
id = int(request.POST.get('task_id'))
the object will probably be deleted; remember that the request parameter's name will be the same as the name of the input (task_id). I recommend using proper CBVs (a DeleteView) for what you want to do - if you want a slow and comprehensive tutorial on that I recommend this article: https://spapas.github.io/2018/03/19/comprehensive-django-cbv-guide/

Django post request doing nothing

So i'm not even sure how to search for someone who had the same thing happen to them.
I'm working on a django website and my form won't post to my database, instead, i get redirected to a URL containing the information that was in the forms, like this:
<form id="form">
<input type="hidden" id="compinp" name="compinp">
<input maxlength="20" onkeyup="showpost()" name="title" id="titleinput">
{{ captcha }}
</form>
Where compinp is some other data that gets posted, {{ captcha }} is a reCaptcha checkbox that works just fine, and when everything is filled in and getting posted, instead of running the post function from views.py, instead i get redirected to this:
http://localhost:8000/newentry/?compinp=XXXX&title=XXXX&g-recaptcha-response="xxxx-xxxx-xxxx"
It gets posted via jQuery through a button outside of the form, though i tried to add a submit button inside it and got the exact same thing.
The views.py function that handles that looks like this:
def newentry(request):
if request.method == "GET" and request.user.is_authenticated():
#creating objects for the view, works fine too
return render(request, "newentry.html",
{"champlist": complist, "captcha": captcha})
elif request.method == "POST" and request.user.is_authenticated():
captcha = Captcha(request.POST)
title = request.POST.get("title", False)
compname = request.POST.get("compinp", False)
comp = Comp.objects.get(title=compname)
if captcha.is_valid() and title and compname:
newe= entry_generator(request.user, title, comp)
newe.save()
return redirect('/')
else:
return redirect('/')
else:
handle_home(request.method, request.user)
This view tries to post models from another app in the same project, if that makes it any different.
I had added a print attempt at the right after the request check for post it didn't print anything.
Not sure what other info i can give to help, if you want any, just ask (:
You need to add the form method post:
<form id="form" method="post">
<input type="hidden" id="compinp" name="compinp">
<input maxlength="20" onkeyup="showpost()" name="title" id="titleinput">
{{ captcha }}
</form>

Flask: redirect to same page after form submission

I have two forms on in my template: one, to post something and the second, to activate file deletion on the server:
<div style="margin-bottom:150px;">
<h4>Delete</h4>
<form method="post" action="/delete">
<div class="form-group">
<input type="hidden" name="delete_input"></input>
</div>
<button type="submit" class="btn btn-danger" id="btnSignUp">Delete</button>
</form>
</div>
<div style="margin-bottom:150px;">
<h4>URLs</h4>
<form method="post" action="/">
<div class="form-group">
<textarea class="form-control" rows="5" id="urls" name="url_area"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="btnSignUp">Urls</button>
</form>
</div>
My app.py looks like this:
#app.route("/")
def main():
return render_template('index.html')
#app.route('/', methods=['POST'])
def parse_urls():
_urls = request.form['url_area'].split("\n")
image_list = get_images(_urls)
return render_template('index.html', images=image_list)
#app.route('/delete', methods=['POST'])
def delete_images():
file_list = [f for f in os.listdir("./static") if f.endswith(".png")]
for f in file_list:
os.remove("./static/" + f)
image_list = []
conn = sqlite3.connect('_db/database.db')
curs = conn.cursor()
sql = "DROP TABLE IF EXISTS images"
curs.execute(sql)
conn.commit()
conn.close()
return render_template('index.html', images=image_list)
Two issues:
I get the form resubmission message when I reload the page after submitting the form
I would like to have one url for everything
The way I see it, I need so use redirects to avoid the duplicate submission and after calling delete, I need to redirect to index.
How can I do this correctly?
I know about redirect and url_for, but how do I redirect to the same page?
You can get the currently requested URL by request.url:
So, to redirect to the same page use:
redirect(request.url)
This worked perfectly for me, in last line:
return redirect(request.referrer)
Change form action to action="{{url_for('delete_images')}}". And for redirection you can use code below:
#app.route('/delete', methods=['POST'])
def delete_images():
return redirect(url_for('delete_images'))
As archer said below:
return redirect(request.referrer)
This is useful when you have a button that uses a route to perform a given function when it is clicked - you don't want to return the user to the URL for that button - you want to return the user to the URL that the button route was referred by, i.e. the page the user was on when they clicked the button.
However, as Mahmoud said:
redirect(request.url)
This is perfect if you perform a function on a page that doesn't use routes or special URLs or anything like that. It essentially just refreshes the page.
One way is set the current url by Javascript in your form. like:
<form method="post" action="/delete">
<div class="form-group">
<input type="hidden" name="delete_input"></input>
</div>
<input type=hidden class=current_url value="" name=current_url>
<button type="submit" class="btn btn-danger" id="btnSignUp">Delete</button>
</form>
And set the hidden input value by JS, like,
function get_current_url() {
var url=window.location.href;
return url
}
$(window).on('load',function(){
var current_url=document.getElementsByClassName('current_url')[0];
current_url.value=get_current_url();
})
At server, redirect to the url that post data

form action not working in django

I have django 1.4 and I am following a tutorial which uses an older version of django. Its a simple tutorial which creates a wiki app with Page as model.
The problem is that the view function corresponding to a POST method in a form is not getting invoked.
This is the content in the urls.py:
url(r'^wikicamp/(?P<page_name>[^/]+)/edit/$', 'wiki.views.edit_page'),
url(r'^wikicamp/(?P<page_name>[^/]+)/save/$', 'wiki.views.save_page'),
url(r'^wikicamp/(?P<page_name>[^/]+)/$', 'wiki.views.view_page'),
This is the content of the template edit.html:
<from method = "get" action="/wikicamp/{{page_name}}/save/">
{% csrf_token %}
<textarea name = "content" rows="20" cols="60">
{{content}}
</textarea>
<br/>
<input type="submit" value="Save Page"/>
</form>
this is link to save
And this is the content in views.py:
def edit_page(request, page_name):
try:
page = Page.objects.get(pk=page_name)
content = page.content
except Page.DoesNotExist:
content = ""
return render_to_response("edit.html", {"page_name":page_name, "content":content}, context_instance=RequestContext(request))
def save_page(request, page_name):
return HttpResponse("You're looking at the page %s." % page_name)
I initially I was getting csrf related error and I then tried all the fixes provided in https://docs.djangoproject.com/en/dev/ref/contrib/casrf/ and followed many many stackoverflow question related to POST and django. Now nothing happens when I click the 'Save Page' button, nothing! Not even any request being sent from the form (Using firebug to track the HTTP request and response)
You have a typo in your HTML: from instead of form.
You may realize this, but that code won't really save anything. I'm not sure what blog you are following, but you would be better-off following the official Django tutorial in the documentation, then reading the forms docs.
You may need to change method to "POST" in your form.
<from method = "get" action="/wikicamp/{{page_name}}/save/">
to
<form method = "post" action="/wikicamp/{{page_name}}/save/">
There are some spelling mistakes, such as from instead of form.
Also the form is malformed.
Change:
this is link to save
to
<input type="submit" value="Save Page" />
And thirdly, change the method= "get"to method="POST".
The entire form should look like this
<form method = "POST" action="/wikicamp/{{page_name}}/save/">
{% csrf_token %}
<textarea name = "content" rows="20" cols="60">
{{content}}
</textarea>
<br/>
<input type="submit" value="Save Page"/>
</form>
Also what #DanielRoseman said. But hey, it might come further down the road.

Categories