Zheng Wang
Zheng Wang

Reputation: 29

Django Ajax Validation

i've been trying to figure out how to use ajax in my django for a while but I coulnt find a solution.

Here is my view.py:

from django.shortcuts import render, render_to_response, RequestContext, HttpResponseRedirect
from .forms import SignUpForm
from django.contrib import messages
# Create your views here.


def home(request):

	form = SignUpForm(request.POST or None)


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


	return render_to_response("home.html",
								 locals(),
								  context_instance=RequestContext(request))

the is the model.py

from django.db import models
from django.utils.encoding import smart_unicode


# Create your models here.

class SignUp(models.Model):
    first_name = models.CharField(max_length=120, null=True, blank=True)
    last_name = models.CharField(max_length=120, null=True, blank=True)
    email = models.EmailField()
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)


    def __unicode__(self):
        return smart_unicode(self.email)

This is the html part

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

I've tried many method but none of them is working . can someone help

Im trying to log a thank you message after the user submitted their information. I want it stay still instead of refreshing. and how to use ajax to replace the built in error message when the email field is empty.

Upvotes: 0

Views: 469

Answers (3)

Yogesh dwivedi Geitpl
Yogesh dwivedi Geitpl

Reputation: 4462

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.

Upvotes: 1

wolendranh
wolendranh

Reputation: 4292

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/')

Upvotes: 0

dazedconfused
dazedconfused

Reputation: 1342

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

Upvotes: 0

Related Questions