Scaffold Your First Django API

Elliott Stein
Nov 7, 2020 · 4 min read

Part I: Environment Setup

Starting any new language or framework can be intimidating. Breathe.

“I’m sure everything I learned in Ruby/Rails will immediately transfer over and apply directly to Django/Python.” — said no one ever

You never realize how much you get for free with Active Record and Rails until you start a new backend framework. After completing my capstone project, I learned:has_many and belongs_to are some of the most powerful code blocks on the planet. Those two lines in a Rails relationship model provide for so many connections throughout your database. That being said, applying yourself to a Django project can teach you a lot more on database structures and relationships.

To get started, you’ll first need to download Python:(https://www.python.org/downloads/). You’ll want to install this globally. I’ve been using Python 3.7.9 and don’t think I’ve run into any issues. I have been told downloading the latest version (at the time of this writing 3.9), can sometimes create dependency issues.

Next, create a project folder in a good place you want to store your files.

After creating a project folder, run the following command while in this directory in your terminal:

virtualenv --python=python3 venv

This just lets your machine know you want all future python commands to equal python3 (so you don’t have to type out python3 every command).

Next:

source venv/bin/activate

This installs a virtual environment within your project’s folder. Creating a virtual environment helps with Django version control when multiple developers are working on the same project. For more detail on this, I thought this was a helpful article: https://medium.com/@dakota.lillie/an-introduction-to-virtual-environments-in-python-ce16cda92853.

I use zsh as a terminal interface, but under most terminals, you should see a (venv) to the left of your folder directory. Now, it’s time to install Django (within the virtual environment):

pip3 install django djangorestframework django-cors-headers

Following installation of these three packages, you can now run:

django-admin start project django_project

I suggest re-naming the django_project folder you just created to src, like this, so that you don’t get confused between the two folder paths:

Image for post
Image for post

Great, now, this is very important, and you should be able to figure out what you’re doing wrong if you don’t do this, but change directories into your src folder now with:

cd src

Within the src folder, run:

python manage.py runserver

If you go to localhost:8000 on your browser, you should see this:

Image for post
Image for post

Congrats!! You’re on Django. Give yourself a pat on the back for taking this leap. Let’s keep going but creating a couple of more basic scaffolding instructions.

The default database for Django is SQLite (same as Rails). SQLite is fine for your microwave, or even your car’s clock, or anything that doesn’t need to be connected to the internet, but wouldn’t be the preferred route to go if you ever plan on deploying your project to the world. To install a PostgresDB package, run:

pip3 install psycopg2

I initially had some troubles setting up Postgres at first, particularly with that last command above. You may get a massive red error message at first, I know myself and another cohort mate of mine did. It’s hard to remember exactly what I did to de-bug, but it wasn’t too difficult to run a couple of commands to move past the error message.

I’ve enjoyed using pgAdmin4 for a Postgres interface. Within PGAdmin, toggle down the server icon on the left and the database icon underneath that. Right click on the database icon and click “create”. This create a database table. Chose a name for your database however you want (e.g. dogs, cats, or animals). Click save and you can close out of PGAdmin.

Back in your code file, delete your SQLite database. The database would have been created after running your server initially. In your settings.py file, within your django project, remove or comment lines 76–81 (any reference to SQLite). Add the following, like so:

# Database# https://docs.djangoproject.com/en/3.1/ref/settings/#databases# DATABASES = {#     'default': {#         'ENGINE': 'django.db.backends.sqlite3',#         'NAME': BASE_DIR / 'db.sqlite3',#     }# }DATABASES = {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2','NAME': 'animals','USER': 'postgres','PASSWORD': "your postgres password goes here",'HOST': 'localhost','PORT': '5432',}}

I learned the hard way that your password MUST be in “double quotes” as opposed to ‘single quotes’ (but I think that only applies if you have special character in your password). You’ve now replaced the SQLite database with your new Postgres database and are ready to start your first Django app.

Run:

python manage.py startapp django_app

You can name your app however you like, but I’ll keep mine as django_app for this guide. Next, add the following 3 apps to your installed apps list (which is already located ~ halfway down in your settings.py file:

INSTALLED_APPS = [...,'django_app','rest_framework','corsheaders',]

Finally, if you want communication with your frontend, add the following line of code to the end of your middleware, as well as the Boolean statement below the array:

MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',]CORS_ORIGIN_ALLOW_ALL = True

Congrats again. You have now completed the basic structure of your first Django Api. Now, you can actually start putting some data together!

For Part II on setting up your Django API, head on over here:

The Startup

Medium's largest active publication, followed by +756K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store