skip to Main Content

I am trying to implement a function using Ajax-JavaScript in which when I click on Activate Option, the value in database for this field changes to ‘Active’ and is displayed on the HTML page as active with Activate Message. If De-Activate is clicked, the text changes to De-Active along with it’s value in the database and show De-Activated message

HTML page:

<div class="col-sm-5">
<div class="panel panel-primary">
 <div class="panel-heading">
   <h3 class="panel-title">Job activation status</h3>
 </div>
   <div class="panel-body">
      <td> Campus Name </td>
      <td> hod_name </td>
      <td>
        <select name="status" class="form-control">
            <option value="1">Active</option>
            <option value="2">Disabled</option>
        </select>
    </td>

  </div>
 </div>
 </div>

Model:

class Campus(models.Model):
    STATUS = (
        ('Active', 'Active'),
        ('Disabled', 'Disabled'),
    )
    campus_name = models.CharField(blank=True, max_length=30)
    hod_name = models.CharField(blank=True, max_length=25)
    status = models.CharField(max_length=10, choices=STATUS, default='Disabled', blank=True)
    def __str__(self):
        return self.campus_name

View:

def status_update(request, pk):
    campus_status = get_object_or_404(Campus, pk=pk)
    campus_status.status = 'Active' if campus_status.status == 'Disabled' else 'Disabled'
    campus_status.save(update_fields=['status'])
    messages.success(request, '{} Status: {} successfully'.format(campus_status.campus_name, campus_status.status))
    return redirect('/dashboard/create_campus/')

2

Answers


  1. HTML page :

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    </head>
    <body>
    <div class="col-sm-5">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <h3 class="panel-title">Job activation status</h3>
            </div>
            <div class="panel-body">
                <table>
                    <tr>
                        <td> {{campus_name}}</td>
                        <td> {{campus_hod}}</td>
                        <td>
                            <select name="status" id="selected_value" onchange="myFunction('{{ campus.id }}')" class="form-control">
                                <option value="1">Active</option>
                                <option value="2">Disabled</option>
                            </select>
                        </td>
                    </tr>
    
                </table>
    
            </div>
        </div>
    </div>
    
    </body>
    
    <script>
        function myFunction(campus_id) {
            let x = document.getElementById("selected_value").value;
            $.ajax({
                url: "/status/update/" + campus_id,
                method: 'POST',
                headers: {'X-CSRFToken': '{{ csrf_token }}'},
                success: function (data) {
                    console.log(data)
                    window.location.replace("/dashboard/create_campus/");
                }
    
            });
    
        }
    </script>
    </html>
    

    URL.py

    from django.urls import path
    from .views import status_update
    urlpatterns = [
        path('status/update/<str:pk>', status_update, name="status update")
    ]
    

    View:

    import json
    
    from django.contrib import messages
    from django.shortcuts import get_object_or_404
    from django.http import JsonResponse
    
    # Create your views here.
    def status_update(request, pk):
        if request.method == 'POST':
            request_data = json.loads(json.dumps(request.POST))
            campus_status = get_object_or_404(Campus, pk=pk)
            campus_status.status = 'Active' if campus_status.status == 'Disabled' else 'Disabled'
            campus_status.save()
            message = {'message': 'Status Updated Successfully', 'status': 'success'}
            messages.success(request,'{} Status: {} successfully'.format(campus_status.campus_name, campus_status.status))
            return JsonResponse(data=message, status=200, safe=False)
    

    Model:

    class Campus(models.Model):
        STATUS = (
            ('Active', 'Active'),
            ('Disabled', 'Disabled'),
        )
        campus_name = models.CharField(blank=True, max_length=30)
        hod_name = models.CharField(blank=True, max_length=25)
        status = models.CharField(max_length=10, choices=STATUS, default='Disabled', blank=True)
        def __str__(self):
            return self.campus_name
    
    Login or Signup to reply.
  2. AJAX is basically an asynchronous request from client side code (i.e JavaScript) and not a Django server side feature. AJAX can be implemented in your Django application using jQuery or any other JavaScript library or framework.

    Refer the below two links for how to implement AJAX in a DJANGO application

    Ajax with jQuery Django example

    Here is the link to another SO answer which has more details.

    I did not modify your code to work with Ajax, I believe you can do it yourself by referring the provided links.

    Please let me know if you have any questions.

    Thanks

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search