Django Render New Result Values From Ajax Request To Html Page
Solution 1:
I am going to present here a minimal application of computation. We give two numbers with the operation wish, django does the calculation and returns the answer in json. Note that, I used the ajax / jquery callback concept and disable the csrf control in the django view with csrf_exempt.
HTML/javaScript:
<div class="container">
<formclass="col-lg-6"id="form"><legend>Select number to make an operation</legend>
Number 1: <inputtype="number"class="form-control"id="n1">
Number 2: <inputtype="number"class="form-control"id="n2">
Select operation:
<selectclass="form-control"name="op"id="op"><optionvalue="+">+</option><optionvalue="-">-</option><optionvalue="*">*</option></select><inputtype="submit"id="submit"value="Send"></form><div><h2class="result-box">The result is : <strongid="result"></strong></h2></div></div><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script><scriptsrc="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script><scripttype="text/javascript">
$(function() {
functioncall_ajax(f) {
const n1 = $('#n1').val();
const n2 = $('#n2').val();
const op = $('#form option:selected').text();
const data = {n1: n1, n2: n2, op: op}
// you can verify the data in the browser consoleconsole.log(data);
$.ajax({
url: '/ajax/make_operation/',
data: data,
type: 'POST',
success: f,
error: function(error) {
console.log(error);
}
});
}
functionserver_response(response) {
// convert to json formatconst r = JSON.parse(response);
console.log(r);
// include the result in the domvar text = document.createElement('i');
text.innerHTML = '<strong id="result">' + r.result + '</strong>';
$('#result').replaceWith(text);
}
//Validate
$('#form').submit(function(e) {
e.preventDefault();
call_ajax(server_response);
});
});
</script></body></html>
views.py:
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
@csrf_exemptdefmake_operation(request):
if request.method == 'POST':
# recovert the data sending by the ajax post request
number1 = int(request.POST['n1'])
number2 = int(request.POST['n2'])
operation = request.POST['op']
print(operation)
result = None# make the operationif operation is'+':
result = number1 + number2
elif operation is'-':
result = number1 - number2
elif operation is'*':
result = number1 * number2
else:
result = number1 + number2
# return the result to the ajax callback functionreturn JsonResponse(json.dumps({'result': result}), safe=False)
return render(request, 'index.html')
urls.py
from django.contribimport admin
from django.urlsimport path
from ajax import views
urlpatterns = [
path('admin/', admin.site.urls),
path('ajax/make_operation/', views.make_operation),
]
So the are many options to do this. I have show only one way to do ajax with django(without django-form).
Solution 2:
In your AJAX success block, you have to tell it what you want it to do with the information:
$(".next-step1").click(function (e) {
var form = $(this).closest("form");
var number1 = $("#CC").val();
var number2 = $("#PP").val();
$.ajax({
url: form.attr("data-validate-number-url"),
data: {
'number1': number1,
'number2':number2
},
dataType: 'json',
success: function (data) {
// 'data' is the dictionary received from the view.// You could call it whatever you want.
$('#sum).html(data.sum_json);
/* Find 'id="sum"' and replace what's inside the tags(or innerHTML)
with the dictionary value of 'sum_json'.
If other keys exist in the 'data' dictionary,
they are accessed the same way, as in 'data.sum_json_2'.
*/
}
});
index.html
<formid="form"action=''data-validate-number-url="{% url 'validate_number' %}"method="POST"enctype="multipart/form-data">{% csrf_token %}
<divclass="form-group col-md-6">
Select the C Raster Dataset:<br><selectname="CC"class="form-control"id="CC"><optionvalue="1">one</option><optionvalue="2">two</option><optionvalue="3">three</option></select>
Select the P:<br><selectname="PP"class="form-control"id="PP"><optionvalue="1">one</option><optionvalue="2">two</option><optionvalue="3">three</option></select>
Select the F:<br><selectname="FF"class="form-control"id="FF"><optionvalue="1">one</option><optionvalue="2">two</option><optionvalue="3">three</option></select></div><buttontype="button"class="btn btn-primary next-step1">Save and continue</button><pid="sum"></p>
Select the GG:<br><selectname="G"class="form-control"id="GG"><optionvalue="1">one</option><optionvalue="2">two</option><optionvalue="3">three</option></select>
Select the JJ:<br><selectname="JJ"class="form-control"id="JJ"><optionvalue="1">one</option><optionvalue="2">two</option><optionvalue="3">three</option></select><buttontype="button"class="btn btn-primary next-step">Save and continue</button>
Select the FINAL:<br><selectname="FINAL"class="form-control"id="FINAL"><optionvalue="1">one</option><optionvalue="2">two</option><optionvalue="3">three</option><optionvalue="10">ten</option></select><buttontype="submit"class="btn btn-primary">Save</button></form>
view
defblog_details(request,slug):
posts=mymodel.objects.all()
post=get_object_or_404(posts, slug_title=slug)
return render(request,'index.html',{'post':post})
defvalidate_number(request):
# You had request.GET, but your form method is POST.
number1 = request.POST.get('number1', None)
print number1
number2 = request.POST.get('number2', None)
print number2
sum=int(number1)+int(number2)
# render a template with the given key: value to be sent to AJAX.
sum_json = render_to_string('sum_template.html', {'sum': sum})
"""
Assuming the information for sum_2 etc. uses the same format,
we can use the same template
"""
sum_json_2 = render_to_string('sum_template.html', {'sum': sum_2})
# Send the dictionary to AJAX. This is what we called 'data'.return JsonResponse({'sum_json': sum_json, 'sum_json_2': sum_json_2})
This is the template that we render_to_string
to send to the AJAX. It renders templates the same way render
does.
sum_template.html
{{ sum }}
You do not want to render_to_string
index.html
because you insert the whole index
template inside the <p>
, not just sum
. You probably also want to add an if
statement to your view
if request.is_ajax() and request.POST:
to filter out the non-AJAX requests.
I've been told there are better ways to do it. I just figured all this out myself, and don't know what they are. If you need more detail let me know.
Post a Comment for "Django Render New Result Values From Ajax Request To Html Page"