[Answer]-Django Ajax Validation

1đź‘Ť

âś…

use these steps to get your desired result ::

views.py”

def home(request):
    if request.method=="POST" and request.is_ajax():
        form = SignUpForm(request.POST)
        if form.is_valid():
            save_it = form.save(commit=False)
            save_it.save()
            return render(request, "thanks.html",{}) 
        else :
            return render(request, "form.html",{'form':form}) 

    form = SignUpForm()
    return render(request, "home.html",{'form':form}) 

then your home.html should be like this:

<html>
# your contents here
<body>
<div id="ajax-form-div">
<form method='POST' id="ajax-form-date" action='your url here'> {% csrf_token %}
    {{ form.as_p }}
    <button id="submit-btn" class='btn btn-success'>Submit</button>
</form>
</div>
</body>
</html>

then you create a new template name “form.html”:

<form method='POST' action=''> {% csrf_token %}
    {{ form.as_p }}
    <input type='submit' class='btn btn-success'>
</form>

Then you create a thanks page like this “thanks.html”:

<div>
<p> Thank you!!!!!!!!!!!!!!!!!!! </p>
</div>

and at the end you write your ajax:

<script>
$.ajax({
    type: "POST",
    url: "URL OF SAME METHOD OR .",
    data: $('#ajax-form-date').serialize()
}).success(function(responce) {
    $("#ajax-form-div").html(responce)
});    
</script>

if form will get valid you will get your thank you mas and if form is not valid you will again get a new form with error msg.

Please take care of jquery should be load on your page. and ajax will get call.

Hope this will help to you.

0đź‘Ť

You’ll need to send an Ajax request using jQuery or XMLHttpRequest Object. (which I didn’t see you doing in the code provided)

For using jQuery, you’ll need to do something like this:

<script>
$.ajax({
    type: "POST",
    url: "url_to_your_view",
    data: $('#id_of_your_form').serialize()
}).done(function(msg) {
    log_thank_you_msg();  // log thank you message using JavaScript or jQuery
});    
</script>

Also, in your view, you can do something like this to return your thank you message:

if form.is_valid():
    save_it = form.save(commit=False)
    save_it.save()
    ...
    return render_to_response("home.html", RequestContext(request, {'message': 'thank you'}))
else:
    handle_the_error()  # Return error messages or do some error handling
👤dazedconfused

0đź‘Ť

Here is jQuery AJAX post with CSRF token:

$(function () {


    $('.btn btn-success').on('click', function (e) {
            // add csrf token to your post
            var csrf = document.cookie.match(/csrftoken=([\w]+)/);
            var data = $('.styled-form').serialize();
            var request = $.ajax({
                    url: window.location.pathname,
                    type: 'post',
                    'csrfmiddlewaretoken' : csrf? csrf[1] : null,
                    'data': data
            });
            // callback handler that will be called on success
            request.done(function (response, textStatus, jqXHR){
                console.log('Success')
                // log a message to the console
            });

            // callback handler that will be called on failure
            request.fail(function (jqXHR, textStatus, errorThrown){
                // log the error to the console
                console.error(
                    "The following error occured: "+
                    textStatus, errorThrown
                );
            });
        }
    });

in view:

if form.is_valid():
    if request.is_ajax():
        save_it = form.save(commit=False)
        save_it.save()
        # messages.success(request, 'Thank you for joining!')
        # return HttpResponseRedirect('/thank-you/')
👤wolendranh

Leave a comment