Django & EmberJS Full Stack Basics: Connecting Frontend and Backend — Part 2

Michael X
8 min readAug 28, 2018

--

In Part 2 we’ll focus on backend development with Django. We will install the required software for backend development, create a new Django project called server, create a new app called books, describe the Book model, register the model with the admin, and demonstrate administration of the database through the Django Admin site.

P1, P2, P3, P4, P5

2.1 Install Software

Before we begin our backend project we’ll need to install some software:

2.1.1 Python

If your MacOS is up-to-date it likely already has Python 2.7 installed. Feel free to use either 2.7 or 3.x. They are essentially the same for the purposes of this tutorial.

Installation is simple. Just download the installer and install as you would a typical MacOS application. Download Python from the official site.

2.1.2 pip

Simply put, pip (Pip Installs Packages) is ‘a package management system used to install and manage software packages written in Python’. Full installation documentation can be found here.

Now, open up the terminal:

# cd into the desktop
cd ~/desktop
# download the pip Python script
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

# run the script
python get-pip.py

# once installation completes, verify that it's installed
pip —-version

2.1.3 virtualenv

virtualenv is a ‘tool to create isolated Python environments… It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either)’.

We can use it to install, modify and play with Python packages and libraries without messing up our global environment. Full installation documentation can be found here.

Now, open up the terminal to install virtualenv:

# use pip to install virtualenv
pip install virtualenv
# verify that it's installed
virtualenv —-version

Let’s create a directory to house our virtual environments:

# cd into the root directory
cd ~/
# create a hidden folder called .envs for virtual environments
mkdir .envs
# cd into the virtual environments directory
cd .envs

We can now create a virtual environment for our project:

# create a virtual environment folder: my_library
virtualenv my_library
# activate the virtual environment from anywhere using
source ~/.envs/my_library/bin/activate

Now that we’ve created a virtual environment called my_library, make sure that the environment is always activated before installing, updating any packages or libraries within the project folder, or running the server.

Finally, take a moment to upgrade pip inside this virtual environment:

pip install -U pip

2.1.4 Django 1.11 (LTS)

Django is described by its creators as a ‘high-level Python Web framework that encourages rapid development and clean, pragmatic design…’

It provides us with a set of common components (i.e. a way to handle user authentication, a management panel, forms, a way to upload files, etc.) so we don’t have to reinvent everything from scratch. Checkout out this DjangoGirls article to learn more about Django and why it’s used.

Although Django is fully capable of handling both frontend and backend tasks, in this project we will be using Django solely to handle the backend. Full installation documentation can be found here.

# inside my_library with virtualenv activated
pip install Django==1.11
# verify that it's installed, open up the Python shell
python
# access the django library and get the version (should be 1.11)
import django
print(django.get_version())
# exit using keyboard shortcut ctrl+D or:
exit()

2.2 Django Project

2.2.1 Create the Django Project: server

Let’s use the django-admin, Django’s ‘command-line utility for administrative tasks’, to generate a new Django project:

# cd into the project folder
cd ~/desktop/my_library

# initialize the virtual environment

source ~/.envs/my_library/bin/activate

# use Django to create a project: server
django-admin startproject server

# cd into the new Django project
cd server
# synchronize the database
python manage.py migrate
# run the Django server
python manage.py runserver

Now visit http://localhost:8000 in your browser and confirm that the Django project is working:

Server running successfully

You can shutdown the server with cmd+ctrl.

2.2.2 Create the Superuser account

We’ll have to create a superuser to login to the admin site and handle database data. Inside my_library/server we run:

# create superuser
python manage.py createsuperuser

Fill in the fields Username, Email Address (optional), and Password. You should get message: Superuser created successfully.

Now run the server with python manage.py runserver and go to http://localhost:8000/admin to see the admin login page. Enter your superuser account details to login.

Logged into the Django Admin site

Nice! We now have access to the Django admin site. Once we create the books model and do the appropriate setup we’ll be able to add, edit, delete, and view book data.

Logout and shutdown the server with cmd+ctrl.

2.2.3 Protecting Our Secrets

Before we do anything else, we’ll want to update the settings.py file to make sure we don’t expose our secrets to the public by accidentally pushing authentication credentials to Github. There are a number of ways of doing this, though I’m going to take the most straightforward path to keep things simple:

# create a config.json file to hold our configuration values
my_library/server/server/config.json

Inside we’ll store our SECRET_KEY value from settings.py under API_KEY:

{
"API_KEY" : "abcdefghijklmopqrstuvwxyz123456789"
}

In settings.py import the json library and load the config variables:

import os
import json
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))with open(BASE_DIR + '/server/config.json', 'r') as config:
obj = json.load(config)
SECRET_KEY = obj["API_KEY"]...

To make sure that config.json with the secret key isn’t pushed to the repository create a .gitignore file in my_library to ignore it (along with some other autogenerated files and the database):

### Django ###
config.json
*.log
*.pot
*.pyc
__pycache__/
local_settings.py
db.sqlite3
media

Now when you commit the changes the files listed above will not be committed. Our secrets are safe and our repo won’t contain unnecessary extra files!

2.3 The Books App

2.3.1 Create the books app

Think of Django apps as modules that plugin into your project. We’ll create an app called books containing the models, views, and other settings for interacting with the books data in the database.

Check out this thread to get a clearer understanding of the differences between projects and apps in Django.

# create new app: books
python manage.py startapp books

# creates directory: my_library/server/books

Now we will install the books app into the server project. Open the settings file: my_library/server/server/settings.py.

Scroll to the INSTALLED_APPS array. Django has installed it's own core apps by default. Install the books app at the end of the array:

INSTALLED_APPS = [
...
'books'
]

2.3.2 Describe the Book model

Next we will describe the Book model in the books app. Open the models file: my_library/server/books/models.py.

Describe a Book model which tells Django that every book in the database will have a title up to 500 characters in length, an author field up to 100, and a description field with an open-ended number:

from django.db import models

class Book(models.Model):
title = models.CharField(max_length=500)
author = models.CharField(max_length=100)
description = models.TextField()

2.3.3 Register the Book model with the admin

Now we will register the Book model with the admin for our books app so that we can view it in the admin site and manipulate the books data from there. Open the admin file: my_library/server/books/admin.py and add:

from django.contrib import admin
from .models import Book

@admin.register(Book)
class bookAdmin(admin.ModelAdmin):
list_display = ['title', 'author', 'description']

With a newly created model we’ll have to make and run migrations so that the database is properly synchronized:

python manage.py makemigrations
python manage.py migrate

Run the server and go to http://localhost:8000/admin to login. Notice that the Book model that was registered with the admin is displayed:

With the ‘Book’ model registered with the admin

Clicking on ‘Books’ displays an empty list because there are no books in the database. Click ‘Add’ to begin creating a new book to add to the database. Go ahead and create a few books.

Add a new book to the database

Once you save and go back to the list, they should be displayed along with it’s title, author, and description (defined in the list_display array).

List of all the books we’ve added to the database

This is great. We can view our database items in the admin panel and create, edit, and delete books from the database through the admin site.

Note: For simplicity’s sake we will be using the SQLite database that comes preinstalled with the creation of every Django project. No need to do any extra work with databases for the purposes of this tutorial.

2.4 Conclusion

Congrats, we made it to the end of Part 2! This is what we’ve done so far:

  • Installed python
  • Used python to install the pip package manager
  • Used pip to install virtualenv to create virtual environments
  • Created a virtual environment in ~/.envs called my_library
  • Activated the my_library environment and upgraded pip
  • Installed Django 1.11 LTS within the my_library environment
  • Created our project directory my_library
  • Created the Django project server
  • Created a superuser account to access the Django admin site
  • Protected our secrets by moving our SECRET_KEY into config.json
  • Ignored files that are autogenerated and/or sensitive with .gitignore
  • Created a new app called books
  • Described the Book model
  • Registered the Book model with the admin
  • Added books data into the database

In Part 3 we will begin work on the REST API (with Django REST Framework) to deliver data to our frontend EmberJS client. The API will have serializers, views, and URLs that will structure our data and pipe it out through endpoints.

That which holds the internet together

--

--

Michael X

Software Developer at Carb Manager | lookininward.github.io | carbmanager.com | Hiring Now! | @mxbeyondborders | /in/vinothmichaelxavier