Send data from a textbox into Flask? - python

I was wondering if there was a way to take something from a text box in the HTML, feed it into flask, then parse that data with Python. I was thinking this might involve some JS but I could be wrong. Any ideas?

Unless you want to do something more complicated, feeding data from a HTML form into Flask is pretty easy.
Create a view that accepts a POST request (my_form_post).
Access the form elements in the dictionary request.form.
templates/my-form.html:
<form method="POST">
<input name="text">
<input type="submit">
</form>
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template('my-form.html')
#app.route('/', methods=['POST'])
def my_form_post():
text = request.form['text']
processed_text = text.upper()
return processed_text
This is the Flask documentation about accessing request data.
If you need more complicated forms that need validation then you can take a look at WTForms and how to integrate them with Flask.
Note: unless you have any other restrictions, you don't really need JavaScript at all to send your data (although you can use it).

Declare a Flask endpoint to accept POST input type and then do necessary steps. Use jQuery to post the data.
from flask import request
#app.route('/parse_data', methods=['GET', 'POST'])
def parse_data(data):
if request.method == "POST":
#perform action here
var value = $('.textbox').val();
$.ajax({
type: 'POST',
url: "{{ url_for('parse_data') }}",
data: JSON.stringify(value),
contentType: 'application/json',
success: function(data){
// do something with the received data
}
});

All interaction between server(your flask app) and client(browser) going by request and response. When user hit button submit in your form his browser send request with this form to your server (flask app), and you can get content of the form like:
request.args.get('form_name')

Assuming you already know how to write a view in Flask that responds to a url, create one that reads the request.post data. To add the input box to this post data create a form on your page with the text box. You can then use jquery to do
var data = $('#<form-id>').serialize()
and then post to your view asynchronously using something like the below.
$.post('<your view url>', function(data) {
$('.result').html(data);
});

This worked for me.
def parse_data():
if request.method == "POST":
data = request.get_json()
print(data['answers'])
return render_template('output.html', data=data)
$.ajax({
type: 'POST',
url: "/parse_data",
data: JSON.stringify({values}),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(data){
// do something with the received data
}
});

Related

Flask - get redirected to new page after POST-request

I have an edit-button on my Site, that will do a POST-Request and then I want to be redirected to new.html, that contains a form, that holds my POST data.
The POST request in my js-file:
async function onEditBtn() {
// find correct entry in schedule
const data = schedule.find(meeting => meeting.id == rowIdOfContextMenu);
rowIdOfContextMenu = -1;
const response = await fetch("editmeeting", {
method: 'POST',
body: data});
}
The receiving Flask-route:
#app.route('/editmeeting', methods=['POST'])
def edit():
data = request.get_json()
print(data)
return render_template('new.html', data)
POST request is succesful, but I am not getting redirected to new.html.
If I use window.location.href = "<route to my edit page>"; or window.location.replace(); on js side using the response I get from the POST request, my edit page won't get the POST-data.
EDIT:
What I was looking for was window.location.href with POST instead of GET.
I ended up using Flask's session object. Did a POST request to /editmeeting, saved the POST-data in a session object, then manually redirected my page to another route rendering new.html using window.location.href in my js-code, and used the data stored in the session.
Thank you for your aswers!
You could add GET method to this function
#app.route('/editmeeting', methods=['GET', 'POST']
or add this to your imports
from flask import Flask, redirect, url_for
and change the return of the function to something like this (only works when 'new' is indeed a function in your app.
return redirect(url_for('new'))

How to redirect to webpage after the function triggered by an Ajax POST is completed

I'm using Flask to build a WebApp. As part of the app I have some tables of data and buttons below that perform certain actions. The buttons work by fetching the <tr> elements of the table that have attribute class="selected", and passing the value of the id attribute to a flask route.
This is the relevant javascript:
function submitDelete(action) {
var data = buildIDPayload(); // which returns a dictionary in form {'ids':[1,2,3]}
$.ajax({
method: "POST",
url: "/delete",
data: JSON.stringify(data),
contentType: 'application/json;charset=UTF-8',
success: console.log('Data Submitted')
});
clearSelections();
};
and this is the Flask route that the data is sent to:
#app.route('/delete', methods=['GET', 'POST'])
#login_required
def delete_users():
data = request.get_json(force=True)
for i in data['ids']:
u = User.query.filter_by(id=i).first()
db.session.delete(u)
db.session.commit()
return redirect(url_for('users'))
The database functionality all works fine, but I'm struggling to have the page refresh in an orderly way. If I set the refresh to occur as part of the success parameter in the ajax POST by setting it to success: location.href = '/users' then that refresh triggers before the flask route is done deleting the user that was passed to it, and this means that they're still present in the table on the refreshed page. On the other hand, if I don't use the succcess parameter to trigger a refresh and instead rely on delete_users() returning a flask redirect...nothing happens at all, it simply never refreshes (though the delete goes through fine).
So; how do I get either ajax or flask to redirect to a URL after the flask route that the ajax POSTed to is done processing it?

Flask with Angular: POST form is empty

I'm sending data via AngularJS POST request:
$http.post('/process', { 'uid': uid, 'action': action }).success(function(response) {
console.log(response);
});
And trying to get sended values in Flask
#app.route('/process', methods = ['POST'])
def process():
return json.dumps({ 'data': request.form.get('uid', 'EMPTY') })
And Flask returns back {"data": "EMPTY"} response. request.form is empty. I've tried to get data from request.data, but it's in strange format there.
I'm learning Python and Flask so I want to do this work with native library, without any other packages right now.
get_json() method helps me
#app.route('/process', methods = ['POST'])
def process():
return json.dumps({ 'data': request.get_json().get('uid') })
If you want to get the data via request.form, you need to have angular send it differently. See this question for details: How can I post data as form data instead of a request payload?
Make sure Content-Type is application/json
Here's a tutorial series on using Flask and AngularJS together - http://tutsbucket.com/tutorials/building-a-blog-using-flask-and-angularjs-part-1/
Hope you'll find it useful.

In Django view,How to save array which pass from template via Ajax, to database?

I create array in JavaScript and send it via Ajax to my view and I can get it in view.Now I want to save it to my database(mysql) but I get "internal error" from Ajax.I think Ajax when post data to view and Django want to connect MySQL database, connection by ajax was abroted.
this is my template Ajax:
var postUrl = "http://localhost:8000/student/{{id}}/student_add_course/";
$('form[name="myForm"]').submit(function(){
$.ajax({
url:postUrl,
type: "POST",
// stock is somthing like this.stock=[[1,12],[2,14],...]
data: {'stock': stock, 'counter':i,csrfmiddlewaretoken: '{{ csrf_token }}'},
error:function (xhr, textStatus, thrownError){
alert(thrownError);},
})
});
this is view:
def student_add_course(request,student_id):
if request.method=='GET':
context={'id':student_id , 'form':AddCourseForStudentForm()}
request.session['ListOfCourses']=[]
return render(request, 'student/AddCourseForStudentForm.html',context)
elif request.is_ajax():
listOFcourses=course_passes.objects.order_by('-id')
id =listOFcourses[0].id
counter=int(request.POST.get('counter'))
for i in range(0,counter):
selected_course=request.POST.getlist('stock[%d][]'%i)
//course_passes is my table.
// evrey thing is good until here but when I want to save it,I get error.
#a.save()
return render(request, 'student/add_course.html')
What is my code problem and How should I solve it?
Is there better way to do this?
I'm sorry for my bad English.
Edit:
Finally I understand my problem is in MySQL side. The value which I want to insert is not correct and I change
a=course_passes(id+1,int(selected_course[0]),int(selected_course[1]),int(student_id))
to
find_user=user.objects.get(user_code=student_id,task=2)
a=course_passes(id+1,selected_course[0],selected_course[1],find_user.id)
thanks for your comment.

What is a best practice to receive JSON input in Django views?

I am trying to receive JSON in Django's view as a REST service. I know there are pretty developed libraries for REST (such as Django REST Framework). But I need to use Python/Django's default libraries.
request.POST is pre processed by django, so what you want is request.body. Use a JSON parser to parse it.
import json
def do_stuff(request):
if request.method == 'POST':
json_data = json.loads(request.body)
# do your thing
Send the response to browser using HttpResponse without page refreshing.
views.py
from django.shortcuts import render, HttpResponse,
import simplejson as json
def json_rest(request):
if request.method == "POST":
return HttpResponse(json.dumps({'success':True, 'error': 'You need to login First'}))
else:
return render(request,'index.html')
urls.py
(r^'/','app.views.json_rest')
client side:
$.ajax({
type:"post",
url: "/",
dataType: 'json',
success: function(result) {
console.log(result)
}
});

Categories