How execute a function contained inside a route on form submit? - python

I have a form. When I submit my form, I want to execute some functions in the route that processes the form data.
Form
<form action="{{ url_for('background_process') }}" method="POST">
<input type="text" id="name" name="name" required />
<input type="url" id="url" name="url"/>
<input type ="text" id="mdp-demo" name= "mdp-demo"/>
<input type=text size=5 name=proglang>
<a href=# id=process_input><button class='btn btn-default'>Submit</button></a>
</form>
Javascript to post form data to route that processes data.
$(function() {
$('a#process_input').bind('click', function() {
$.getJSON('/background_process', {
proglang: $('input[name="proglang"]').val(),
url: $('input[name="url"]').val(),
title: $('input[name="name"]').val(),
dates: $('input[name="mdp-demo"]').val(),
}, function(data) {
$("#result").text(data.result);
});
return false;
});
Route that processes the form data.
#app.route('/background_process', methods=['GET','POST'])
def background_process():
try:
create_table()
data_entry()
url = request.args.get('url', 0, type=str)
title = request.args.get('title', 0, type=str)
dates = request.args.get('dates', 0, type=str)
if url.lower() == 'https://www.reddit.com/':
return jsonify(result='You are wise')
else:
return jsonify(result='Try again.')
except Exception as e:
return str(e)
I want to execute the create_table() and data_entry() functions when the submit button on the form is clicked.
The result at the moment is that nothing happens. These functions work when executed on app run time outside of a route. It's when they are within a route they don't work. Any suggestions as to what I should do to achieve execution of these functions inside my route?

Related

Ajax send single data on button click

I am using parametrized ajax to send data to flask on button click. The data and buttons are in for loops and I want ajax to send single data but it's sending multiple items. The data sent back to flask only repeats for the first dictionary in the list, and is only the value for the first key in the dictionary. The rest generates an error.
Flask code
from Flask import flask,request
app = Flask(__name__)
all_items = [{'name':'sausage','price':10},{'name':'soda','price':50}]
#app.route('/index', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('index.html', all_items = all_items)
Ajax script:
<script type=text/javascript>
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data : {
item : $('#item').val(),
price: $('#price').val(),
},
type : 'POST',
url : '/index'
})
.done(function(data) {
//nothing
});
event.preventDefault();
});
});
</script>
Html:
{%for item in all_items%} <!--all_items is a list of dictionaries-->
<form>
<fieldset>
<input type="hidden" name="item" id="item" value="{{item.name}}">
<input type="hidden" name="price" id="price" value="{{item.price}}">
<input type="submit" name="submit" id="submit" value="Add to Cart" class="button" />
</fieldset>
</form>
{% endfor %}

Django form submit without refreshing

thanks in advance. I know this has been asked a few times. But after reading the previous questions, reading and understanding JSON and AJAX forms tutorials, I still can't find a way to not having the website refreshed after submitting a form. I would really appreciate it if any of you with a higher knowledge of JavaScript is able to give a hand.
This is a newsletter at the bottom part of the Home page that just asks for a name and an email and it keeps the information in the database, it works perfect and I just would like to reply with a confirmation message without refreshing, because it replies a message but the user has to go to the bottom of the page again to see it which is not practical at all.
The HTML is
<div id="contact_form">
<div class="Newsletter">
<form id="form" enctype="multipart/form-data" method="POST" action="" style="text-align: left;">
{% csrf_token %}
<div class="fields">
<div class="fields">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" minlength="3" placeholder="e.g. John Smith" id="name" required>
</div>
<div class="fields">
<label for="email" id="email_label">Email</label>
<input type="email" name="email" placeholder="e.g. john#example.com" id="email" required>
</div>
</div>
<div class="submit">
<button type='submit' id="submit" >Subscribe</button>
</div>
{% include 'messages.html' %}
</form>
</div>
</div>
The index view
def index(request):
"""View function for home page of site."""
if request.method == 'POST':
form = NewsUserForm(request.POST)
if form.is_valid():
instance = form.save(commit=False) #we do not want to save just yet
if NewsUsers.objects.filter(email=instance.email).exists():
messages.warning(request, 'Your email already exists in the newsletter database')
else:
instance.save()
messages.success(request, 'Great! Your email has been submitted to our database.')
try:
send_mail('Welcome ', 'Thank you for subscribing to the Newsletter. ', 'user123#gmail.com',[instance.email], fail_silently=False)
except BadHeaderError: #add this
return HttpResponse('Invalid header found.') #add this
form = NewsUserForm()
return render(request, 'index.html', {'form':form})
Most of the tutorials suggest to create another view + an url for that view + ajax code
I tried this one from here (https://pytutorial.com/how-to-submit-a-form-with-django-and-ajax#top) without success, also eliminating "post" in html method but still not working, even the info got from the form appears in the url. Any help will be welcome, thank you very much.
jquery unsuccessful code
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
type : "POST",
url: "{% url 'index' %}",
data: {
name : $('name').val(),
email : $('email').val(),
csrfmiddlewaretoken: '{{ csrf_token }}',
dataType: "json",
},
success: function(data){
$('#output').html(data.msg) /* response message */
},
failure: function() {
}
});
});
unsuccessful ajax view function and url
def ajax_posting(request):
if request.is_ajax():
name = request.POST.get('name', None) # getting data from first_name input
email = request.POST.get('email', None) # getting data from last_name input
if name and email: #cheking if first_name and last_name have value
response = {
'msg':'Your form has been submitted successfully' # response message
}
return JsonResponse(response) # return response as JSON
#path('ajax-posting/', views.ajax_posting, name='index'),# ajax-posting / name = that we will use in ajax url

Django view return value with AJAX

I am working with Django and AJAX,
I have a template where people can select an option and then click a submit button. The button fires an Ajax function that sends the data to my view where it is processed and should return a value back to the template.
The issue is when the post goes through, it hits the view, and nothing is returned to the template, I am not sure if this is because the view isn't getting any data, but it isn't firing any of my conditional statements, so it acts like its working but doesn't return anything.
My HTML form:
<form method="POST" id="buy_form" name="buy_form" action="{% url 'manage:buy' %}">
{% csrf_token %}
<div class="buy_top_section">
<div class="width">
<div class="spacing">
<h3 class="sell_title">How much do you want to sell?</h3>
<input type="text" id="amount" class="buy_input_top" maxlength="10" name="amount" type="number" required>
<select id="selected" class="buy_selection" name="wanted">
<option value="generate_b">BTC</option>
<option value="generate_e">ETH</option>
<option value="generate_l">LTC</option>
</select>
</div>
<span class="float_clear"></span>
<button id='generate' type="submit" value="currency_details" class="custom_button"l">Generate
</button>
</div>
</div>
</form>
<!-- What needs to be returned from thew view -->
<h1>{{ address }}</h1>
My AJAX
$(document).on('submit', '#buy_form', function (e) {
e.preventDefault()
$.ajax({
type: 'POST',
url:'/manage/buy/',
data:{
currency:$('selected').val(),
amount:$('#amount').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success: function (){
}
})
});
My Django View
def buy_corsair(request):
if request.method == 'POST':
if request.POST.get('wanted') == 'generate_b':
# Get the amount entered
amount = request.POST.get('amount')
# Generate a new B address
new_b_address = client.create_address(b_account_id)['address']
# Point the address at the user
request.user.user_address.b_address = new_b_address
# Save address to current user
request.user.user_address.save()
# Pass the address to the template
context = {'address': new_b_address}
return render(request, context)
urls.py
urlpatterns = [
# Buy Page
path('buy/', views.buy_corsair, name='buy'),
]
Ajax requests run in background, django render function render a template to body, so you can not render this way. You could like this;
dont forget include
from django.http import HttpResponse
def buy_corsair(request):
if request.method == 'POST':
if request.POST.get('wanted') == 'generate_b':
# Get the amount entered
amount = request.POST.get('amount')
# Generate a new B address
new_b_address = client.create_address(b_account_id)['address']
# Point the address at the user
request.user.user_address.b_address = new_b_address
# Save address to current user
request.user.user_address.save()
# Pass the address to the template
return HttpResponse(new_b_address)
in your js;
$.ajax({
type: 'POST',
url:'/manage/buy/',
data:{
currency:$('selected').val(),
amount:$('#amount').val(),
'csrfmiddlewaretoken': "{{ csrf_token }}"
},
success: function (data){
$('h1').html(data);
}
})
});
in your Django view
import json
from django.http import HttpResponse
def buy_corsair(request):
if request.method == 'POST':
if request.POST.get('wanted') == 'generate_b':
# Get the amount entered
amount = request.POST.get('amount')
# Generate a new B address
new_b_address = client.create_address(b_account_id)['address']
# Point the address at the user
request.user.user_address.b_address = new_b_address
# Save address to current user
request.user.user_address.save()
# Pass the address to the template
context = {'address': new_b_address}
return HttpResponse(json.dumps(context))
in your js
$.ajax({
type: 'POST',
url:'/manage/buy/',
data:{
currency:$('selected').val(),
amount:$('#amount').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success: function (response){
console.log(response);
//access the value and print it in console//
var obj=JSON.parse(response)["address"];
alert(obj);
}
})
});

Submit without refresh in django

i have a html form and submit button (It adds or removes relations in manytomanyfield "users"):
{% if user in event.users.all %}
<form action="/event/{{ event.id }}/" method="GET">
<input type="hidden" value="{{ event.id }}" name="remove">
<input type="submit" value="Remove">
</form>
{% else %}
<form action="/event/{{ event.id }}/" method="GET">
<input type="hidden" value="{{ event.id }}" name="add">
<input type="submit" value="Add">
</form>
in views.py:
def show_event(request, event_id):
...
event = get_object_or_404(Event, id=event_id)
user = request.user
if request.GET.get('add'):
event.users.add(user)
event.save()
if request.GET.get('remove'):
event.users.remove(user)
event.save()
return render(request, 'events/event.html', {'event':event, 'user':user,})
This function works fine, but the page refreshes after submitting form. I need no refresh and i need to change button text just like "Follow" button in Twitter. I tried to use some jquery\ajax but i dont exactly understand how it should work. Can please anyone explain how to do it? Thanks.
Here's an extremely basic ajax example. In your form, you can fire your ajax method with:
<a onclick="AjaxFormSubmit()" href="#">Submit</a>
Then your ajax method would be as follows:
function AjaxFormSubmit() {
$.ajax({
url : '/event/{{ event.id }}/',
type : "POST",
data : { the_post : $('#id-of-your-field').val() }
}).done(function(returned_data){
// This is the ajax.done() method, where you can fire events after the ajax method is complete
// For instance, you could hide/display your add/remove button here
});
}
I recommend looking at the Ajax documentation to see all of the Ajax methods available to you.
Also, in your view, you'll need to return (in this example) json data via an HttpResponse. i.e.
return HttpResponse(json.dumps(your_data))
# I like to return success/fail Booleans, personally
*Note, this is untested code.

Angular.js http.post request 404 with flask

im getting a bad request, here is my url code:
#app.route('/login', methods=['POST'])
def login():
print(request)
user = models.User.get(models.User.email**request.form['email'])
if request.form['password'] == user.rpe:
login_user(user)
return jsonify(user.to_json())
here is my html:
<form id="form">
<input type="email" placeholder="email" id="email" name="correo">
<input type="password" placeholder="rpe" id="password" name="password">
<button type="submit" ng-click="submit()">Log in</button>
</form>
and here is my js code:
$scope.submit = function(event){
var form = $('form');
var values = {};
$.each(form.serializeArray(), function(i, field){
values[field.name] = field.value;
});
data = JSON.stringify(values);
console.log(data);
$http.post('/login', values).success(function () {
alert('success');
});
}
after i do the request with the form, here is what i get:
<Request 'http://localhost:8000/login' [POST]>
im guessing that this request isnt what it is suppoused to be, im also asking because in other questions some user added a csrf token but i actually dont know how to add one with javascript since im adding my angular app this way:
#app.route('/')
def main():
return make_response(open('templates/index.html').read())
thanks

Categories

Resources