w/ Django Rest Framework & Postgres

Rio Weber
Rio Weber
Jan 26, 2018 · 3 min read

Prerequisites:

Install Python3
Good Luck

Install Postgres
https://postgresapp.com/

Install Postico
https://eggerapps.at/postico/

Project: Mr. Django

./START

First create the directory for the project.

mkdir mrdj

cd to that directory.

cd mrdj

Create a Python virtual environment.

python3 -m venv .

Activate the environment.

source bin/activate

Install python packages.

# REQUIRED
pip install django
pip install djangorestframework
# Postgres
pip install pillow
pip install psycopg2

Echo requirements to requirements.txt to save dependencies.

pip freeze > requirements.txt

Make New Django Project

django-admin startproject mrdj

cd to the project.

cd mrdj/

RUN THE SERVER

./manage.py runserver

TADA!


TO CONNECT TO POSTGRES DATABASE

Open settings.py

/Users/riordenweber/projects/mrdj/mrdj/mrdj/settings.py

Locate this code:

Change to:

Add rest_framework to INSTALLED_APPS

Save File.

Running ./manage.py runserver now will throw an error.
This is because it is looking for a postgres database named mrdj

Create Postgres Database (mrdj)

Using Postico:

Create a new Database and Name it mrdj.

Restart Server.

Will get warning.

You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run ‘python manage.py migrate’ to apply them.

Apply migrations for default Django Tables

python manage.py makemigrations

Should get none.

Migrate

python manage.py migrate

Refresh Postico.

Will see the tables created by Django.


MAKE NEW SUPERUSER

Now we make a new superuser

./manage.py createsuperuser

I always make mine with:
username: admin
email blank
password: admin

Now you can go to http://127.0.0.1:8000/admin/ and log in.


MAKE REST API TO CREATE/DELETE/GET USER(s)

To do this requires 4 things.

  1. ROUTER (Uses URLs)
  2. URLS (Requires a Viewset)
  3. VIEWSET (Requires a Serializer)
  4. SERIALIZER

First Open urls.py and change to:

Running the server will throw this error:
NameError: name ‘UserViewSet’ is not defined

Create UsersViewSet

Make new file viewsets.py

/Users/riordenweber/projects/mrdj/mrdj/mrdj/viewsets.py

Running the server will throw this error:
ModuleNotFoundError: No module named ‘mrdj.serializers’

Create Serializers

Create new file serializers.py

/Users/riordenweber/projects/mrdj/mrdj/mrdj/serializers.py

a


./END

riow

Publications are personal

Rio Weber

Written by

Rio Weber

It doesn’t get better than this.

riow

riow

Publications are personal

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade