Basic web app with Django Rest Framework and JQuery-ajax

Christopher Shoo
8 min readApr 8, 2018

If you are learning django and you have reached a point where you want to build web Api, django rest framework is probably a good choice to start with. It offers the ability to convert your python code to raw json format and it also provides you with simple interface that enables you to browse through your api.

On this post i am going to show you how to create a simple api with django rest framework and how to interact with it using jquery ajax. For the purpose of simplicity the api is going to provide students information which includes first name, last name, age and gender.

creating the api

first we have to create a virtual environment. I recommend you to use virtual environments on your projects because they isolate your projects from each other. This is helpful because it helps to avoids conflicts between different sets of packages required by different projects, for example you can work on two projects running on different versions of django and there will be no conflicts between the two. Also when you want to host your project to a server, with virtual environments each project will be deployed with it’s own packages without conflicts with the other deployed apps on the same server.

To create virtual environment on linux first you need to have virtualenv installed on your machine, run the following commands on the terminal to install, i am using arch linux if you are using other linux distributions google some steps to do this on your distribution.

$ yaourt virtualenv

it will give you a lot of packages, choose python-virtualenv and follow the procedures to install it. if you are not familiar with using yaourt follow this link how to install packages with yaourt.

run the following commands to create and activate the virtual enviroments

$ mkdir restapi
$ cd restapi/
$ virtualenv env
$ source env/bin/activate
(env) $

you can change the name of the directories and the name of the virtual environment, i named mine env you can choose any. To make sure you are working in the virtual environment the name of your virtual environment will appear first before the dollar sign just like i have shown.

To get started we need to install several packages required to make an api, if you are following along with me run the following commands to install the packages

(env) $ pip install django==1.11
(env) $ pip install djangorestframework

the first command will install django and the second will install the rest framework, i assume you understand how to create a new project with django-admin so i wont put much explanations on that.

$ django-admin startproject students
$ cd students/
$ django-admin startapp info

add the following apps on your settings file under INSTALLED_APPS list

'rest_framework',
'info', # put the name of your app here, mine is info

create your model in the models.py file, if you are following along mine looks like this

from django.db import modelsclass Students(models.Model):
Female = 'F'
Male = 'M'
choices = ((Female, 'Female'), (Male, 'Male'))
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
age = models.IntegerField()
gender = models.CharField(max_length=1, choices=choices, default=Female)

run the following migration commands to migrate the model we have created together with other necessary models that are used with installed apps in the INSTALLED_APPS list

$ python manage.py makemigrations
$ python manage.py migrate

here you can register the model to the admin page and add a few students from there but to shorten this post we are not going to that, instead we are going to add the students from the python shell, run the $ python manage.py shell to enter the python shell and do the following commands

>>> from info.models import Students
>>> student = Students.objects.all()
>>> student.create(first_name='sara', last_name='klause', age=15, gender='F')
<Students: sara>
>>> student.save()
>>> quit()

run the third command several times to create several students. In the app directory (info for the case of this post) create new file called serializers.py with the command touch info/serializers.py (assuming you have not changed the directory ) and put the following code

from rest_framework import serializers
from .models import Students
class studentSerializer(serializers.ModelSerializer):
class Meta:
model = Students
fields = '__all__'

the imported serializers from the rest_framework at the first line enables us to convert the models objects ( the added students in the database ) to json format. To do that we inherit from ModelSerializer class from serializers and provide it with the class to serialize (Students) and specify the fields to serialize, those are the fields we will get from the json data, i have put all fields but you can do it like fields = ['first_name', 'last_name']to create the list of fields to be serialized from the class

in the views.py file put the following code

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Students
from .serializers import studentSerializer
class Get_students_List(APIView):
def get(self, request):
students = Students.objects.all()
serialized = studentSerializer(students, many=True)
return Response(serialized.data)
def homepage(request):
return render(request, 'index.html')

in the above code we have created the view ( Get_students_list ) that inherits from APIView, this will handle the requests to the api and enables us to return the response using django rest framework response we have imported at the third import. In the view class we have defined the method get to handle get requests, you can add more methods to handle more requests such us post requests after you have a clear understanding of what is going on but for this post we are going to just return the data with get request. From the get function we have obtained the students objects which is basically all the students in the database and we have used the studentSerializer class we have created earlier to serialize the objects in the students list. The serialized variable now has the json data and on the last line we have returned the response which contains the data. The homepage function will render our front end template which in your case is the website and from the template we will use the jquery to work with the data. Note that we are not passing the data on the render function as we used before, that is because we don’t need to, because we are getting it from the api we are creating.

modify the url.py file and add new urls, one to point to the api view function and the other to point to the homepage function we have created, if you are following along here is what the url.py looks like

from django.conf.urls import url
from django.contrib import admin
from info import views
urlpatterns = [
url(r'^home$', views.homepage),
url(r'^studentsapi$', views.Get_students_List.as_view()),
url(r'^admin/', admin.site.urls),
]

at this point the api will be ready and you can test it by running the server and run the curl command with the other terminal as follows

$ python manage.py runserver
$ curl localhost:8000/studentsapi

the list of students will be shown in the json format, it will look like this

[
{"id":1,"first_name":"john","last_name":"doe","age":14,"gender":"M"},{"id":2,"first_name":"sara","last_name":"klause","age":15,"gender":"F"}
]

or you can go to the url localhost:8000/studentsapi and the you will see the api browsable version

we said earlier the advantages of using virtual environments is that it helps you to simplify the work of knowing which packages are required for the site to run and also installing them, in order to use that advantage run the following commands

$ pip install pipreqs
$ pipreqs .

that will create a file requirements.txt which will have all the packages needed to run the site. You can see what is in there to confirm by running the more command more requirements.txt

$ more requirements.txt
Django==1.11
djangorestframework==3.8.2

the Frontend

at this point part we are going to access the api using jquery-ajax by requesting the json data and view them on our website.

create the folder called templates in the app directory with and add the index.html file with the following commands

$ mkdir info/templates
$ touch info/templates/index.html

in the index.html file add the following html code, note that i am keeping it simple for the case of this post.

<!DOCTYPE html>
<html>
<head>
<title>students api</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div>
<button class="apireq">click me </button>
</div>
<div id="jsonresp" style="margin-top: 100px">
<p><label> First name :</label> <span id="first_name"></span></p>
<p><label> Last name :</label> <span id="last_name"></span></p>
<p><label> age :</label> <span id="age"></span></p>
<p><label> gender : </label> <span id="gender"></span></p>
</div>
<script type="text/javascript"></script>
</body>
</html>

the above page has a button and when you click it, student info is going to appear from the database. To make this possible add the following jquery code at the script file, note that this is not what you will do on the production site, you will probably put your js code on the static directory and do some configurations to access it.

$('.apireq').click( function() {
$.ajax({
url : "http://localhost:8000/studentsapi",
dataType: "json",
success : function (data) {
$('#first_name').text( data[0].first_name);
$('#last_name').text( data[0].last_name);
$('#age').text( data[0].age);
$('#gender').text( data[0].gender);
}
});
});

when the button is clicked the code above will send the request to the api using the $.ajax() function and fill in the student info at the fields we have set on our html template. The jquery ajax function takes the plain object parameter and this object contains the settings that configures the request sent by the $.ajax() function, on this we have used three of them but there are more of them and you probably are going to use them on the production site to get more flexibility, you can learn about them on this link jQuery.ajax API documentation

url: specifies the url that we are making a request to, in our case we use the api url , we also specify the data type we want to get from the response as json but you could use others like html, success: parameter provides the function to be called if the request is successful and in our case the function fills the student info in the index.html template.

on your browser go to the url localhost:8000/home and click the button, you will see the information about a student

you can modify the code and put some loops there to get the info of all the students in the database but that’s it you have successfully created the api and interacted with it using jquery

learn more on rest framework : rest framework documentation

thank you for taking your time reading this, i hope you have learned something new, i am also learning so if you have some suggestions please be free to give them

--

--

Christopher Shoo

I like building stuff with python and react, and by the way! i use arch!.