Skip to content

hiro9108/Create-API-with-Django

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Create API with Django

Check python environment

python -v
pip -v

Install virtualenv

pip install virtualenv

Create virtualenv

virtualenv {name}

source {name}/bin/activate

Create django project

django-admin startproject {Project_name}

cd {Project_name}

Install Django

pip install django

Move to project folder

cd {Project_name}

Create django application

django-admin startapp {App_name}

1. Check django admin

python manage.py migrate

python manage.py createsuperuser

2. setup django

Reference: https://bit.ly/3jpvmOQ

3. setup PostgreSQL

Install postgreSQL

brew install postgresql

Install check

psql -V

Start PostgreSQL

brew services start postgresql

Check

brew services list

check default database

psql -l

check default database

psql -l

create user

createuser -P postgres

Create database

createdb demo_api -O postgres;
pip install dj_database_url
pip install python-dotenv
pip install psycopg2-binary

In setting.py.

(TOP line)
---
from dotenv import (find_dotenv, load_dotenv)
import dj_database_url
---


(Override database setting line)
---
load_dotenv(find_dotenv())
DATABASES = {
    'default': dj_database_url.config(conn_max_age=600)
}
---

Create .env in top directory.

DATABASE_URL=postgres://postgres:postgres@localhost/demo_api

*DATABASE_URL=postgres://{username}:{password}@localhost/{DBName}

Connect from django and check admin site

python manage.py makemigrations
python manage.py migrate

python manage.py createsuperuser
python manage.py runserver

4. setup cors

Install cors library

pip install django-cors-headers

Add corsheaders to setting.py

INSTALLED_APPS = [
    ...
    'corsheaders',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
     ...
]

---Last line---

CORS_ORIGIN_ALLOW_ALL = True

---

https://pypi.org/project/django-cors-headers/

5. Prepare for Deploying to Heroku

Install libraries

pip install whitenoise
pip install gunicorn

Modify setting.py

---Near Top---
import os

DEBUG = False

ALLOWED_HOSTS = ['*']
---



MIDDLEWARE = [
    ...
    'whitenoise.middleware.WhiteNoiseMiddleware',
]

---Near STATIC_URL---

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

---

http://whitenoise.evans.io/en/stable/

Create a Procfile file in top directory.

web: gunicorn {project_folder name}.wsgi

Execute the command in top directory.

pip freeze > requirements.txt

6. Deploy to Heroku

Connect github to heroku by using GUI.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages