🔖 Day20 - Django from scratch (A simple API)

2018 - 06 - 26
🔖 Day20 - Django from scratch (A simple API)
0. [TL;DR] This is a brief summary of building a simple Django App / API. Recently, I built another project CountryRestAPI for generating a list of states in a country in JSON format. During the process, I was surprised quit a number of construction steps for building a Django Project I forgot. In order to let myself remember the procedures firmly, a note should be written to recall anytime. If you are new and interest to Django, then this post is going to help. I am going to build a simple API as example.
1. [Install Python]
  • Download installation packages from https://www.python.org/downloads/mac-osx/.
  • Mac has default Python as Python2. Nowadays, we usually use Python3 so we have to tell Mac to recognize Python3 as default. To do so, open terminal and type:
    $alias python='python3'
  • Recently Python3.6.4 is released. If you have Python3.6.3 and wish to upgrade it, you will have to uninstall current version first. Open terminal and type:
    $sudo rm -rf /Applications/Python\ 3.6/
    Then download and install the updated version from official website again
  • Check the current version of Python from terminal:
    $python --version

2. [Install Django (using pipenv) And Start A Project] The advantages of using pipenv is to isolate current project from the others and have control on the packages versions. For instance, you wish to use Django1.11 for some projects while using Django2 for current project.
  • Create a folder where you believe you will use Django for all projects, then change directory into this folder from terminal:
    $mkdir django2
    $cd django2
  • Install Django from terminal:
    $pipenv install Django==2.0.2 
    (In case you wish to specify the version of Django as 2.0.2) Now a file named pipfile is created by pipenv.
  • Starting up a Django project:
    $pipenv run django-admin.py startproject PROJECT_NAME
    A new project folder named as PROJECT_NAME is now created where you can see a file named manage.py.
  • Change working directory on terminal:
  • Start a new Django app under the project:
    $pipenv run django-admin.py startapp APP_NAME
    A new app folder named APP_NAME is created under the project folder PROJECT_NAME. Python files including admin.py are also created in the app folder.
  • Before the app is available, you have to register it under INSTALLED_APP in PROJECT_NAME/settings.py. Open the settings from your text/code editor, then add the this:

3. [Install postgresql and pgAdmin] Django comes with sqlite as default database. However, it is recommended to use postgresql since many PaaS such as Heroku does not support sqlite.
  • Download and install postgres.app from http://postgresapp.com/.
  • Graphical interface such as pgAdmin is recommended for create/backup/manage postgres database. Download and install pgAdmin form https://www.pgadmin.org/download/.
  • Open up postgres.app and it will show up on the top right menu of MacOS.
  • Configure user/owner (usually leave it as postgres) and your password.
  • Open up pgAdmin on Mac, configure and connect to the postgres.app. From the dropdown list on the left, expand servers and find postgresql. Expand to see databases, right click to create new database for your Django project, owner as postgres.

4. [Python-decouple(.env) and Create Simple progject with Django] Let's say we want to create a project containing a table of country names, using postgresql as database. Project name is myapi, app name is country and database name is countryDB in postgres.
  • Install python-decouple which will be used to protect your privacy. Open terminal, change directory into project folder myapi:
    $pipenv install python-decouple
  • In your favourite text/code editor, open myapi/settings.py and edit the following: Copy and paste the settings of SECRET_KEY and DEBUG to a new .env file under myapi folder. Like these:
    SECRET_KEY = 'yr28q3horh2pq8238ruq2u3r2qprbuc8qp' e.g.
    DEBUG = True
    Then head back to myapi/settings.py and modify:
    from decouple import config
       SECRET_KEY = config('SECRET_KEY')
       DEBUG = config('DEBUG', default=False, cast=bool)
    This is the way you use python-decouple whenever you think the settings should not be disclosed to the others.
  • Roll down to database session, change the database from sqlite into postgresql:
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': 'countryDB',
            'USER': 'postgres',
            'PASSWORD': config('DBPASSWORD'),
            'HOST': '',
            'PORT': '5432',
    Noted that database password is also set under .env with decouple.
  • Install psycopg2 which is used as an adapter between Python and PostgreSQL:
    $pipenv install psycopg2
    It is informed that psycopg2 will change their name soon. They suggest developer to install psycopg2-binary instead.
  • After installing this adapter, Django can now contact the database. Makemigrations and migrate things to the database first:
    $pipenv run python manage.py makemigrations
    $pipenv run python manage.py migrate
  • Create Django superuser form terminal in order to manage the project:
    $pipenv run python manage.py createsuperuser
  • Now we can add our data into the database. In editor, open country/models.py and add model(which is table in database):
    class Country(models.Model):
        name = models.CharField(max_length=100)
        code = models.CharField(max_length=10)
  • Open country/admin.py and add the model into admin session:
    from .models import Country
  • Inform Django that we have create new model by making migrations: Open terminal:
    $pipenv run python manage.py makemigrations
    $pipenv run python manage.py migrate
  • Now you can use the terminal to GET/POST/UPDATE/DELETE the model. For instance to add a country:
    $pipenv run python manage.py shell
    $from country.models import Country
    Then you have a new row in the database table, with 'name' as 'Australia'
  • Says you want to let people to search the country name by using their code, e.g. 'au' for Australia, you will need to assign urls and views to do so. First assign a url pattern. Go to country/urls.py and add these:
    from django.urls import path, re_path
       from country import views as cv
       urlpatterns = [
          path('admin/', admin.site.urls, name='admin'),
          re_path(r'([\w]{2})', cv.find_country, name='find_country'),
    So now, url such as 'http://yourdomain.com/au' is available. (note: only 2 characters allowed as assigned in regex)
  • Write a view for generating the ORM from server instead of shell. Go to country/views.py:
    from .models import Country
       from django.http import JsonResponse
       def find_country(request, key):
            target = Country.objects.get(code=key)
            data = {'code': target.code, 'name':target.name}
            return JsonResponse(data)
    As a result, when user look up url (http://yourdomain.com/au), a JSON format is present like this: {'code': 'au', 'name': 'Australia'}


There is no comment yet

New Comment

Please Login to comment