How Can I run a python function in script file or in the views.py using javascript for not loading the page

Viewed 438

I have a Django page that has a form that has a button that calls functions in the views.py, but I want to validate some input text of the form via running a python script function (in views.py or I can separate this function in another file) but I don't want to load the page. where and How can I make js code to run this function?

2 Answers

Create a new url to for a the view function which will validate the input.

path('ajax/validate_input/', views.ValidateInput.as_view(), name='my_ajax_url'),

In views.py do your validation then return a JsonResponse.

from django.views import View
from django.http import JsonResponse

class ValidateInput(View):
    def post(self, request):
        # Do validation
        return JsonResponse({
            'valid': True,
            'message': 'Invalid Characters',
        })

Now in your template write js code that will make ajax requests to that url.

According to received response make changes to your webpage using js in the success of your ajax.

// add jQuery
// put the code below inside an event handle, maybe on input change
$.ajax({
    url: {% url 'my_ajax_url' %},
    method: 'POST',
    data: {
        body: body,
        csrfmiddlewaretoken: '{{ csrf_token }}'
    },
    dataType: 'json',
    success: function(data){ 
        console.log(data.valid);
        console.log(data.message);
        // do stuff to change your webpage here
    }
});

I would recommend validating input on input change, but if you want to do it in from submit, then add an event handler for form submit. There use event.preventDeafault to prevent form submit, then do the ajax stuff, and according to the received json do something else. Maybe if valid = true then proceed further or if valid = false then show the message received in json below the input box.

You could render the form in a dedicated Python view and invoke it via Ajax from Javascript.

In this view you should:

  • create the form
  • render it to a string
  • return rendered form as json

If you invoke it via GET method, you render the form with initial values (no warnings or errors messages).

If used method is POST, you get values from the request and render the form (including validation messages).

This could be how the Django view looks like:

import json
from django.http import HttpResponse
from django.template.loader import render_to_string

def my_view(request):

    if request.method == "GET":    
        form = MyForm()
    elif request.method == "POST":
        form = MyForm(data=request.POST)

    form_context = {'form': form}    
    form_html = render_to_string('form.html', form_context)

    json_response = json.dumps(form_html, separators=(',', ':'))
    return HttpResponse(json_response)

In the Javascript side via GET (using JQuery.getJSON):

$.getJSON('/url/path/to/my-view',
          function(data) {
              var form_html = decodeURIComponent(data.form);
              $("form#my-form-css-selector").html(form_html);
});

And in the Javascript side via POST (using JQuery.post):

$.post('/url/path/to/my-view',
       $("form#my-form-css-selector").serialize(),
       function(data) {
           var form_html = decodeURIComponent(data.form);
           $("form#my-form-css-selector").html(form_html);
       },
       "json"
);

You can check Django views, Django render_to_string, JQuery.getJSON, JQuery.post doc pages for further info.

Related