Debug School

rakesh kumar
rakesh kumar

Posted on

How to display json data in template file in django

To display student data using a JSON response in a template file using jQuery, follow these step-by-step instructions:

Create a view in Django:

Open your Django app's views.py file.
Import the necessary modules and classes.
Create a view function to retrieve student data and return a JSON response.
Example:

from django.http import JsonResponse
from .models import Student

def student_list(request):
    students = Student.objects.all().values()
    return JsonResponse(list(students), safe=False)
Enter fullscreen mode Exit fullscreen mode

Create a template:

Create a new HTML file called student_list.html in your app's templates directory.
Add an empty

    element to the template to hold the student data. Example:
<h1>Student List</h1>
<ul id="student-list"></ul>

Add jQuery to the template

Image description

Define the URL pattern:

Open your Django project's urls.py file.
Import the view function from your app's views.py file.
Define a URL pattern that maps to the student_list view function.
Example:

from django.urls import path
from your_app.views import student_list

urlpatterns = [
    # Other URL patterns
    path('students/', student

Using Serializer method

To display student data using a JSON response and jQuery in a template file, follow these step-by-step instructions:

Define the Student model:

Open your Django app's models.py file.
Define the Student model with the required fields.
Example:

from django.db import models

class Student(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    roll_number = models.IntegerField()
    # Add other fields as per your requirements

Create a serializer:

Create a new file called serializers.py in your Django app's directory.
Import the serializers module from rest_framework.
Define a serializer class for the Student model.
Example:

from rest_framework import serializers
from .models import Student

class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = '__all__'

Create a view:

Open your Django app's views.py file.
Import the necessary modules and classes.
Create a view function to retrieve student data and return a JSON response.
Example:

from django.http import JsonResponse
from .models import Student
from .serializers import StudentSerializer

def student_list(request):
    students = Student.objects.all()
    serializer = StudentSerializer(students, many=True)
    return JsonResponse(serializer.data, safe=False)

Create a template:

Create a new HTML file called student_list.html in your app's templates directory.
Add an empty ul element with an id attribute to the template to hold the student data.
Example:

<h1>Student List</h1>
<ul id="student-list"></ul>

Add jQuery to the template:

<script>
$(document).ready(function() {
    // Make an AJAX request to retrieve the student data
    $.ajax({
        url: '/students/',  // Replace with the URL mapped to your view function
        dataType: 'json',
        success: function(data) {
            // Loop through the data and populate the <ul> element
            for (var i = 0; i < data.length; i++) {
                var student = data[i];
                var listItem = '<li>' + student.first_name + ' ' + student.last_name + ' - Roll Number: ' + student.roll_number + '</li>';
                $('#student-list').append(listItem);
            }
        }
    });
});
</script>

Image description

Image description

Image description

Define the URL pattern:

Open your Django project's urls.py file.
Import the view function from your app's views.py file.
Define a URL pattern that maps to the student_list view function.
Example:

from django.urls import path
from your_app.views import student_list

urlpatterns = [
    # Other URL patterns
    path('students/', student

Top comments (0)