How to use ajax in django,to pass the model object and store it in database without refreshing the page?

i'm doing a small project in django,in that i thought of adding a favorite button in one of the pages so that on clicking on that button it has to return the model object and it has to be stored in another database for the reference,but its not happening Here is my home/bookdetails.html

i'm doing a small project in django,in that i thought of adding a favorite button in one of the pages so that on clicking on that button it has to return the model object and it has to be stored in another database for the reference,but its not happening Here is my home/bookdetails.html

  <!DOCTYPE html>

{% extends 'home/Base.html' %}

{% block title %} Book Details {% endblock %}
{% load staticfiles %}

<link rel="stylesheet" href="{{ STATIC_URL }}/home/css/heart.css">
<script src="{% static 'js/heart.css' %}"></script>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="{% static 'js/app.js' %}"></script>

{% block body %}

{% if error_message %}<p><strong> {{ error_message }} </strong></p>{% endif %}
<script type="text/javascript">
$(document).ready(function(){
$("#sub").click(function(event) {
var userbooks = '{{ userbooks }}';
$.ajax({
type: "GET",
url: "{% url 'home:favoriteAjax' %}"
data:{userbbooks:userbooks}
datatype:'json'
success: function() {
alert("successfully added to favorites")
}
}
});
});
});

</script>
<p>Book name:{{ userbooks.book_name }}</p><br>
<p>Book author:{{ userbooks.book_author }}</p><br>
<p>Book genre:{{ userbooks.book_genre }}</p><br>
<p>Book ISBN:{{ userbooks.book_ISBN }}</p><br>
<button type="submit" id="sub" onclick="changeText()">Favourite</button>

{% endblock %}

my urls.py:

from django.urls import path
from . import views
app_name='home'
urlpatterns=[
path('',views.HomeView,name='home'),
path('addBooks/',views.addBooks,name='addBooks'),
path('myBooks/',views.BooksView.as_view(),name='myBooks'),
path('<int:pk>/', views.BookDetailsView.as_view(), name='myBooks'),
path('search/', views.SearchedBooks.as_view(), name='searchedBooks'),
path('favorite_ajax/', views.favorite_ajax, name='favoriteAjax'),
]

my models.py:

from django.db import models
from django.contrib.auth.models import User
class UserBooks(models.Model):
user_id = models.ForeignKey(User,on_delete=models.CASCADE,null=True)
username = models.CharField(max_length=200)
book_name = models.CharField(max_length=200)
book_author = models.CharField(max_length=200)
book_ISBN=models.CharField(max_length=200)
book_genre = models.CharField(max_length=200)
book_status=models.BooleanField(default=False)
class Meta:
unique_together = (("username", "book_ISBN"),)
def str(self):
return self.book_name

class FavBooks(models.Model):
user_id = models.ForeignKey(User,on_delete=models.CASCADE,null=True)
book_id= models.ForeignKey(UserBooks,on_delete=models.CASCADE,null=True)
class Meta:
unique_together = (("user_id", "book_id"),)

my views.py:

def favorite_ajax(request):
if(request.method=='GET'):
book=request.GET['userbooks']
fav=FavBooks()
fav.book_id=book
fav.user_id=request.user
fav.save()
return HttpResponse("done")

i want to take the userbooks model object from the bookdetails.html through ajax call and want to store that reference in the FavBooks model how could i make it happen?

Django 2 Ajax CRUD with Python 3.7 and jQuery

Django 2 Ajax CRUD with Python 3.7 and jQuery

In this tutorial, you'll learn how to send Ajax requests in Django 2 and Python 3.7 to add CRUD operations in your application and manipulate your Django models and database without having to refresh your web pages each time.

Originally published  at techiediaries.com on 17 Dec 2018

Ajax stands for Asynchronous JavaScript and XML and it's a way for getting data from the server and updating the page on the fly without refreshing the page.

Creating a Virtual Environment

Make sure you have Python 3 installed (Python 3.7 is the latest as of this writing) and start by creating a virtual environment for your project's packages:

$ python -m venv myenv

Next, activate your virtual environment using:

$ source myenv/bin/activate
Installing Django 2 and Creating a Project

Now, you need to install Django using pip:

$ python -m pip install django

Next, create a Django project using:

$ django-admin startproject djangoajaxdemo

Next you need to create a Django application using the manage.py script:

$ cd djangoajaxdemo
$ python manage.py startapp rooms

Next you need to add it to your project's installed apps array in the settings.py file:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rooms'
]
Adding jQuery

In this tutorial, we'll be using jQuery to send Ajax requests to Django. You can also use any other HTTP client like Axios, the JavaScript Fetch API available on modern browsers or the XMLHttpRequest interface.

First of all, you need to get jquery from the official website and include it in your project or use a CDN. Go to the official website and get the CDN of the version of jQuery you want to use.

In my case, I'll be using jQuery 3.3.1 from https://code.jquery.com/jquery-3.3.1.min.js.

Inside the rooms application, create a templates/rooms folder and create a base.html file:

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> Django Ajax CRUD with jQuery</title>
<link  rel="stylesheet"  href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"   crossorigin="anonymous">
</head>
  <body>
    <div class="container d-flex h-100">
      <div class="row justify-content-center">
        <div class="col-10">
          {% block main %}
          {% endblock %}
        </div>
      </div>
    </div>
{% block js %}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
{% endblock %}
{% block extrajs %}
{% endblock %}
  </body>
</html>
Adding a Model

We'll be adding CRUD operations against a Room model. Open the rooms/models.py file and add the following code:

from django.db import models

class Room(models.Model):
ROOM_TYPES = (
(1, 'Single'),
(2, 'Double'),
(3, 'Triple'),
)

name = models.CharField(max_length=50)
status = models.CharField(max_length=30, blank=True)
room_number = models.IntegerField(blank=True, null=True)
nobeds = models.IntegerField(blank=True, null=True)
room_type = models.PositiveSmallIntegerField(choices=ROOM_TYPES)

Adding CRUD Views

In the rooms/views.py file add the following class based and generic views for performing CRUD operations:

from django.views.generic import View
from django.http import JsonResponse
from django import forms
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.forms.models import model_to_dict
from .models import Room

class RoomForm(forms.ModelForm):
class Meta:
model = Room
fields = 'all'

class RoomList(View):
def get(self, request):
rooms = list(Room.objects.all().values())
data = dict()
data['rooms'] = rooms
return JsonResponse(data)

class RoomDetail(View):
def get(self, request, pk):
room = get_object_or_404(Room, pk=pk)
data = dict()
data['room'] = model_to_dict(room)
return JsonResponse(data)

@method_decorator(csrf_exempt, name='dispatch')
class RoomCreate(CreateView):
def post(self, request):
data = dict()
form = RoomForm(request.POST)
if form.is_valid():
room = form.save()
data['room'] = model_to_dict(room)
else:
data['error'] = "form not valid!"
return JsonResponse(data)

class RoomUpdate(View):
def post(self, request, pk):
data = dict()
room = Room.objects.get(pk=pk)
form = RoomForm(instance=room, data=request.POST)
if form.is_valid():
room = form.save()
data['room'] = model_to_dict(room)
else:
data['error'] = "form not valid!"
return JsonResponse(data)

class RoomDelete(View):
def post(self, request, pk):
data = dict()
room = Room.objects.get(pk=pk)
if room:
room.delete()
data['message'] = "Room deleted!"
else:
data['message'] = "Error!"
return JsonResponse(data)

Next, let's add the urls. Open the urls.py file and add:

from django.urls import path, include
from django.views.generic.base import TemplateView
from rooms import views

urlpatterns = [
path('rooms/', TemplateView.as_view(template_name="rooms/main.html"), name='room_main'),
path('rooms/list', views.RoomList.as_view(), name='room_list'),
path('rooms/create', views.RoomCreate.as_view(), name='room_create'),
path('rooms/update/<int:pk>', views.RoomUpdate.as_view(), name='room_update'),
path('rooms/delete/<int:pk>', views.RoomDelete.as_view(), name='room_delete'),
path('rooms/<int:pk>', views.RoomDetail.as_view(), name='room_detail'),
]

Adding a Template

Since we'll be using Ajax for making CRUD operations in our Django application we will not need multiple pages or templates but instead we'll conceive our application as a Single Page Application.

Let's create a main.html file inside the rooms/templates/rooms folder with the following content:

{% extends 'rooms/base.html' %}
{% block main %}
{% endblock %}

{% block extrajs %}
<script src="{% static 'js/app.js' %}"></script>
{% endblock %}

Next under your project's root folder create the static/js/ folder and add an app.js file with the following content:

$(function () {
console.log("Hello!");
});

In your urls.py file, add the following url pattern so you can access your static files in development mode:

from django.conf import settings

[...]

if settings.DEBUG:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()

In the settings.py file, add the following setting to configure your static folder:

STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)

If your run your application and visit the http://127.0.0.1:8000/rooms/ you should see a Hello! in the console of your browser which means you static files are configured correctly.

In this tutorial, we'll implement the list and delete operations. For create and update operations we'll see them in the next tutorial.

Getting Rooms with jQuery.ajax()

In your app.js file, add the following code to get data from the rooms/list endpoint by sending a GET Ajax request:

$.ajax({
url: '/rooms/list',
type: 'get',
dataType: 'json',
success: function (data) {
let rows = '';
data.rooms.forEach(room => {
rows += &lt;tr&gt; &lt;td&gt;${room.room_number}&lt;/td&gt; &lt;td&gt;${room.name}&lt;/td&gt; &lt;td&gt;${room.nobeds}&lt;/td&gt; &lt;td&gt;${room.room_type}&lt;/td&gt; &lt;td&gt; &lt;button class="btn deleteBtn" data-id="${room.id}"&gt;Delete&lt;/button&gt; &lt;button class="btn updateBtn" data-id="${room.id}"&gt;Update&lt;/button&gt; &lt;/td&gt; &lt;/tr&gt;;
});
$('#myTable > tbody').append(rows);
$('.deleteBtn').each((i, elm) => {
$(elm).on("click", (e) => {
deleteRoom($(elm))
})
})
}
});
Deleting Rooms with jQuery.ajax()

Next, you need to add an implementation for the deleteRoom(e) method:

function  deleteRoom(el){
roomId = $(el).data('id')
$.ajax({
url: /rooms/delete/${roomId},
type: 'post',
dataType: 'json',
success: function (data) {
$(el).parents()[1].remove()
}
});
}

Now go back to your rooms/templates/rooms/main.html template and add the table:

{% block main %}
<table class="table table-bordered" id="myTable">
<thead>
<th>
Room Number
</th>
<th>
Name
</th>
<th>
Number of Beds
</th>
<th>
Type
</th>
<th>
Actions
</th>
</thead>
<tbody>
</tbody>
</table>

<div id="roomform">
<button id="createRoom" class="btn"> Create Room </button>
</div>

{% endblock %}

This is a screenshot of our page at this point:

In the next tutorial, we'll see how to create a form and send it with jQuery and Ajax to our Django endpoints to create and update rooms.

Originally published  at techiediaries.com on 17 Dec 2018

===================================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Complete Python Bootcamp: Go from zero to hero in Python 3

☞ Python and Django Full Stack Web Developer Bootcamp

☞ Python for Time Series Data Analysis

☞ Python Programming For Beginners From Scratch

☞ Beginner’s guide on Python: Learn python from scratch! (New)

☞ Python for Beginners: Complete Python Programming

☞ Django 2.1 & Python | The Ultimate Web Development Bootcamp

☞ Python eCommerce | Build a Django eCommerce Web Application

☞ Python Django Dev To Deployment

Python Django Tutorial | Django Course

Python Django Tutorial | Django Course

🔥Intellipaat Django course: https://intellipaat.com/python-django-training/ 👉This Python Django tutorial will help you learn what is django web development &...

This Python Django tutorial will help you learn what is django web development & application, what is django and introduction to django framework, how to install django and start programming, how to create a django project and how to build django app. There is a short django project as well to master this python django framework.

Why should you watch this Django tutorial?

You can learn Django much faster than any other programming language and this Django tutorial helps you do just that. Our Django tutorial has been created with extensive inputs from the industry so that you can learn Django and apply it for real world scenarios.

Ajax Form Submit examples using jQuery

Ajax Form Submit examples using jQuery

In this jquery ajax form tutorial – you have learned how to send or submit the form data or multipart form using the jquery ajax on the server. Also, you have known the related queries of jquery ajax form.

Overview

In this jQuery Ajax submits a multipart form or FormData tutorial example – you will learn how to submit the form using the jquery ajax with multi-part data or FromData. Here you will know about the basic faqs of jquery ajax form.

In this tutorial, learn jquery ajax form submits with the form data step by step. A simple jQuery Ajax example to show you how to submit a multipart form, using Javascript FormData and $.ajax().

If you will be using jQuery’s Ajax Form Submit, you can send the form data to the server without reloading the entire page. This will update portions of a web page – without reloading the entire page.

AJAX: AJAX (asynchronous JavaScript and XML) is the art of exchanging data with a server and updating parts of a web page – without reloading the entire page.

Table Of Contents

  • Create HTML Form
  • jQuery Ajax Code

FAQs

  • How to add extra fields or data with Form data in jQuery ajax?
  • ajax FormData: Illegal invocation
  • How to send multipart/FormData or files with jQuery.ajax?

Create HTML Form

In this step, we will create an HTML form for multiple file uploads or FormData and an extra field.

<!DOCTYPE html>
<html>
<title>jQuery Ajax Form Submit with FormData Example</title>
<body>
 
<h1>jQuery Ajax Form Submit with FormData Example</h1>
 
<form method="POST" enctype="multipart/form-data" id="myform">
    <input type="text" name="title"/><br/><br/>
    <input type="file" name="files"/><br/><br/>
    <input type="submit" value="Submit" id="btnSubmit"/>
</form>
 
<h1>jQuery Ajax Post Form Result</h1>
 
<span id="output"></span>
 
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> 
 
</body>
</html>

jQuery Ajax Code

In this step, we will write jquery ajax code for sending a form data to the server.

$(document).ready(function () {
 
    $("#btnSubmit").click(function (event) {
 
        //stop submit the form, we will post it manually.
        event.preventDefault();
 
        // Get form
        var form = $('#fileUploadForm')[0];
 
       // Create an FormData object 
        var data = new FormData(form);
 
       // If you want to add an extra field for the FormData
        data.append("CustomField", "This is some extra data, testing");
 
       // disabled the submit button
        $("#btnSubmit").prop("disabled", true);
 
        $.ajax({
            type: "POST",
            enctype: 'multipart/form-data',
            url: "/upload.php",
            data: data,
            processData: false,
            contentType: false,
            cache: false,
            timeout: 800000,
            success: function (data) {
 
                $("#output").text(data);
                console.log("SUCCESS : ", data);
                $("#btnSubmit").prop("disabled", false);
 
            },
            error: function (e) {
 
                $("#output").text(e.responseText);
                console.log("ERROR : ", e);
                $("#btnSubmit").prop("disabled", false);
 
            }
        });
 
    });
 
});

FAQs – jQuery Ajax Form Submit

1. How to add extra fields with Form data in jQuery ajax?

The **append()** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.

// Create an FormData object 
    var data = new FormData(form);
 
// If you want to add an extra field for the FormData
    data.append("CustomField", "This is some extra data, testing");

2. ajax FormData: Illegal invocation

jQuery tries to transform your FormData object to a string, add this to your $.ajax call:

processData: false,
contentType: false

3. How to send multipart/FormData or files with jQuery.ajax?

In this step you will learn how to send multiple files using jQuery ajax. Let’s see the below code Snippet:

var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
    data.append('file-'+i, file);
});
 
$.ajax({
    url: 'upload.php',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    method: 'POST',
    success: function(data){
      console.log('success');
    }
});

Note

Conclusion

In this jquery ajax form tutorial – you have learned how to send or submit the form data or multipart form using the jquery ajax on the server. Also, you have known the related queries of jquery ajax form.