Django Ajax PUT Request Example Tutorial

Published On: 22/08/2022 | Category: Django


Hi Dev,

This article will provide example of django ajax put request example. you will learn how do i put with jquery/ajax in django. In this article, we will implement a jquery ajax put json response example. This tutorial will give you simple example of how do i get data from my ajax put to my django view. So, let's follow few step to create example of django ajax patch request example tutorial.

When you click on the edit button then we will open the model with username and email input and then we will save data using the ajax put method. you can edit data using jquery ajax get in django all version as well.

Now let's move on to the PUT request. In our current scenario we have to edit users user profile with ajax PUT request.

This should look similar to a POST request. The only difference is the shape of the URL:

Here i explained simply step by step example of django ajax put request example.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2: Create a App
python3 manage.py startapp core
Step 3: Update setting.py

In this step we require to do add installed apps in our settings.py file. Add the below lines to your settings.py file:

Next, you need to add it in the settings.py file as follows:

settings.py

....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]
Step 4: Creating the Views

In this step, we need to create the views for performing fetch record to the database.Open the core/views.py file and add:

core/views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.models import User
from django.http import JsonResponse,HttpResponse
from django.http import HttpResponse
import json

# Create your views here.
def user_list(request):
    users = User.objects.all()
    return render(request, "home.html", {"users": users})

def update_user(request,id):
    if request.method == 'PUT':
        obj = get_object_or_404(User, id=id)
        data = json.load(request)

        username = data.get('username')
        email = data.get('email')

        obj.username=username
        obj.email=email
        obj.save()

        return JsonResponse({'success':'User Updated Successfully!'})
    else:
        return JsonResponse({'errors':'Something went wrong!'})
Step 5: Creating the Templates

Next, open the core/templates/home.html file and the add:

core/templates/home.html
<!DOCTYPE html>
<html>
<head>
    <title>Django Ajax PUT Request Example  - Tuts-Station.com</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
        
<div class="container mt-5 pt-5">
    <h2>Django Ajax PUT Request Example - <span class="text-primary">Tuts-Station.com</span></h2>
    
    <table class="table table-bordered data-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th width="120">Action</th>
            </tr>
        </thead>
        <tbody>
            {% for user in users %}
                <tr data-id="{{ user.id }}">
                    <td>{{ user.id }}</td>
                    <td>{{ user.username }}</td>
                    <td>{{ user.email }}</td>
                    <td>
                        <a 
                            href="javascript:void(0)" 
                            id="edit-user" 
                            class="btn btn-primary"
                            >Edit</a>
                    </td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
 
</div>
 
<!-- Modal -->
  
<div class="modal fade" id="userEditModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Edit User</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
      
            <div class="modal-body">
                <input type="hidden" id="user-id" name="id"></span>
                <p><strong>Name:</strong> <br/> <input type="text" name="username" id="user-name" class="form-control"></span></p>
                <p><strong>Email:</strong> <br/> <input type="email" name="email" id="user-email" class="form-control"></span></p>
            </div>
      
            <div class="modal-footer">
                <button type="button" class="btn btn-success" id="user-update">Update</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
      
</body>
 
<script type="text/javascript">
      
    $(document).ready(function () {
  
        /*------------------------------------------
        --------------------------------------------
        When click user on Edit Button
        --------------------------------------------
        --------------------------------------------*/
        $('body').on('click', '#edit-user', function () {
   
            $('#userEditModal').modal('show');
            $('#user-id').val($(this).parents("tr").find("td:nth-child(1)").text());
            $('#user-name').val($(this).parents("tr").find("td:nth-child(2)").text());
            $('#user-email').val($(this).parents("tr").find("td:nth-child(3)").text());
 
       });
      
        /*------------------------------------------
        --------------------------------------------
        When click user on Show Button
        --------------------------------------------
        --------------------------------------------*/
        $('body').on('click', '#user-update', function () {
   
            var id = $('#user-id').val();
            var username = $('#user-name').val();
            var email = $('#user-email').val();
  
            $.ajax({
                url: '/users/update/' + id,
                type: 'PUT',
                dataType: 'json',
                data: JSON.stringify({username: username, email: email,}),
                headers: {
                    "X-CSRFTOKEN": "{{ csrf_token }}"
                },
                success: function(data) {
                    $('#userEditModal').modal('hide');
                    alert(data.success);
  
                    $("tr[data-id="+id+"]").find("td:nth-child(2)").text(username);
                    $("tr[data-id="+id+"]").find("td:nth-child(3)").text(email);
                }
            });
  
       });
         
    });
    
</script>
      
</html>
Step 6: Creating URLs

In this section, we’ll create the urls to access our CRUD views.Go to the urls.py core/urls.py file and update it as follows:

core/urls.py
from django.urls import path
from core import views

urlpatterns = [
    path('users/', views.user_list, name="user_list"),
    path('users/update/<int:id>', views.update_user, name="update_user"),
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
]
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/users/ address with a web browser.

I Hope It will help you....