Installing Django and Django-REST Framework on ubuntu

Django REST framework is a powerful and flexible toolkit for building Web APIs. Some reasons you might want to use REST framework:

Following post details about how you can get started with simple helloproject example to setup DJANGO REST Framework.

$ mkdir workspace 
$ cd workspace 
$ sudo apt-get install python3-venv 

Following command, Creates a new virtual environment by running,

$ python3 -m venv PATH_TO_CREATE_ENVIRONMENT_DIRECTORY 

Note: You can set any directory for virtual environment, lets say we want to create environment in current directory, then you can use below command but if you want create environment in “/home/devlab/virtualenvs” directory, the below command will be “python3 -m venv /home/devlab/virtualenvs”

$ python3 -m venv env 

The final step in setting up your virtual environment is to activate it:

$ source env/bin/activate 

Now, we need to install “django” and “django rest framework” using below command,

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

Now, we are ready to start the project,

(env)$ django-admin startproject helloproject . 

Notice: the dot ( . ) at the end of command.

Once you run above command, you will see following new files getting created,

(env)$ tree helloproject/
helloproject/
├── asgi.py
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
$ cd helloproject 
$ django-admin startapp helloapp 
(env)$ tree
.
├── asgi.py
├── helloapp
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── __init__.py
├── __pycache__
│   ├── __init__.cpython-36.pyc
│   ├── settings.cpython-36.pyc
│   └── urls.cpython-36.pyc
├── settings.py
├── urls.py
└── wsgi.py

$ cd .. 

Now sync your database for the first time,

$ python manage.py migrate 
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying sessions.0001_initial... OK
$ tree helloproject/
helloproject/
├── asgi.py
├── helloapp
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── __init__.py
├── __pycache__
│   ├── __init__.cpython-36.pyc
│   ├── settings.cpython-36.pyc
│   └── urls.cpython-36.pyc
├── settings.py
├── urls.py
└── wsgi.py

We’ll now create an initial user named “admin" with a password of “password123". We’ll authenticate as that user later in this example.

$ python manage.py createsuperuser --email social@lynxbee.com --username admin 
Password: 
Password (again): 
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

here, we used “password123” which is too weak, and it showed with a message as “This password is too common” , so you can choose to set any password.

Once you’ve set up a database and the initial user is created and ready to go, open up the app’s directory and we’ll start coding…

Serializers

First up we’re going to define some serializers. Let’s create a new module named helloproject/helloapp/serializers.py that we’ll use for our data representations. [ As we can see, by default we don’t have helloproject/helloapp/serializers.py ]

$ vim helloproject/helloapp/serializers.py 
from django.contrib.auth.models import User, Group
from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'groups']


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ['url', 'name']

Views

Now, we need to create some views,

$ vim helloproject/helloapp/views.py 
from django.shortcuts import render

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from helloproject.helloapp.serializers import UserSerializer, GroupSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

# Create your views here.

URLs

$ vim helloproject/urls.py 

by default, this urls.py file will have following code,

"""helloproject URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
]

change this to,

from django.contrib import admin
from django.urls import include, path
from helloproject.helloapp import views
from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

Pagination

Pagination allows you to control how many objects per page are returned. To enable it append the following lines to helloproject/settings.py

$ vim helloproject/settings.py 
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

Settings

Add 'rest_framework' to INSTALLED_APPS. The settings module will be in helloproject/settings.py

INSTALLED_APPS = [
    ...
    'rest_framework',
]

Now, we can start the server as,

$ python manage.py runserver 
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
June 03, 2020 - 19:43:33
Django version 3.0.7, using settings 'helloproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Leave a Comment