Richard Smith
Richard Smith

Reputation: 337

Django request in html

I have set up django to work in my local environment. I have a python function which takes two parameters and returns data in JSON format. This is set up in my views.py and urls.py as follows:

views.py :

from django.http import Http404, HttpResponse
from X import calculate

def calculate_X(request, para1, text):
    #para1 is ignored on purpose
    return HttpResponse(calculate(text))

urls.py :

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^calculate-X/(\d+)/([a-zA-Z0-9_ ]*$)',calculate_X),
    url(r'^$', TemplateView.as_view(template_name='base.html')),
] 
urlpatterns += staticfiles_urlpatterns()

In the base.html file I have a single button which should make the request to the calculate-x url as follows /calculate-X/1/stringdataexample

which would then create an alert() with the contents of the httpresponse ( JSON )

How can I make this request?

(There is another question asked here on SO however it uses request processors which do not relate to my question)

Upvotes: 0

Views: 504

Answers (1)

Agustin Castro
Agustin Castro

Reputation: 281

one way could be to trigger an ajax call when you click that button, and then process the response as you wish.

The button's html could be something like this:

<button onclick="processCalculation()">Calculate!</button>

Something like this function:

function processCalculation(){
  var para1 = $("#params-container").val();
  var text = $("#text-container").val();
  $.ajax({
       url: "/calculate-X/" + para1 + "/" + text,
       data: {}
    }).done(function (jsonResponse) {
        alert(jsonResponse)
 });

}

I hope this points you on the right direction, Best regards!

Upvotes: 1

Related Questions