potato tomato
potato tomato

Reputation: 47

How to integrate Django form with Ajax?

I've gone through many tutorials in how to integrate ajax with django form but all were complicated. I have a Signup model with Signup form and a views like the following. models.py

from django.db import models

class SignUp(models.Model):
    name = models.CharField(max_length=120, blank=True, null=True)
    email = models.EmailField()

    def __unicode__(self):
        return self.email

and forms.py

from django import forms
from .models import SignUp

class SignUpForm(forms.ModelForm):
    class Meta:
        model = SignUp
        fields = ['name', 'email']

    def clean_name(self):
        name = self.cleaned_data.get('name')
        return name 

    def clean_email(self):
        email = self.cleaned_data.get('email')

        try:
            match = SignUp.objects.get(email=email)
        except SignUp.DoesNotExist:
            return email

        raise forms.ValidationError('This email address is already subscribed.')

views.py

from django.shortcuts import render
from django.core.mail import send_mail
from django.conf import settings 

from .forms import SignUpForm

def index(request):
    form = SignUpForm(request.POST or None)

    if form.is_valid():
        name = form.clean_name()
        email = form.clean_email()
        instance = form.save()

        subject = 'Bruke Church news'
        from_email = settings.EMAIL_HOST_USER
        to_email = [email]
        contact_message = "%s:Thank you for signing up for our newsletter via %s. we'll be in touch" %( 
                                        name,
                                         email)

        send_mail (subject, 
                            contact_message, 
                            from_email, 
                            to_email,
                            fail_silently=False)
    context = {
        "form": form
    }
    return render(request, "index.html",context)

and my html form looks like this

<form action="" method="POST">
                  {% csrf_token %}
                  {{form|crispy}}
                  <input type="submit" value="Sign up" class="btn btn-primary">
                </form>

This code runs well but it loads the full page and I want to load only the form. After googling, I found a concept of Ajax but am really having problem in doing so. please help me Thank you

Upvotes: 1

Views: 292

Answers (1)

Ssravankumar Aditya
Ssravankumar Aditya

Reputation: 489

Example of Ajax Post on button click submit

this method needs to run

put this in your HTML

function AddData(){
    var name = $("#name").val();
    var email = $("#email").val();

    // You should extract each and every id from your form fields


    var signupData = { name:name, csrfmiddlewaretoken: '{{ csrf_token }}',email:email};
    $.ajax({
                type: "POST",
                url: "../../index/",
                data: signupData,
                success: function(data) {
                                        alert("You Have Sucessfully Signed Up ");

                                                                    },
                                        statusCode: {
                                                      500: function() { 
                                                                        alert("You Have Already Signed Up ");
                                                                       }
                                                      },
                                    })
    }

In your Views.py

def index(request): 
    if request.method == 'POST': # From Frontend we are getting the data in a POST method and we are checking if front end is giving POST Method or not 
        get_email = request.POST.get('email') # Taking The DATA from front end in form of POST to Django  USER EMAIL ADDRESS
        get_name = request.POST.get('name')# Taking The DATA from front end in form of POST to Django NAME
        queryset_list = SignUp.objects.all().values_list("email",flat=True)# Performing a Django Query and getting all Signup Email Address
        if get_email in queryset_list:
           return HttpResponse(status=500)
        else:
           SignUp.objects.create(name=get_name,email=get_email)
    return HttpResponse('')

Upvotes: 2

Related Questions