DEV Community

Cover image for Django API Project Setup
Saad Alkentar
Saad Alkentar

Posted on

Django API Project Setup

What to expect from this article?

Well, let's start coding! This is the first coding article. After introducing the idea of Alive Diary and proving that Gemini can be the soul, we will start coding the Backend with Django.
To keep things in order, I'll discuss the project through multiple articles, so this article

  • will cover the project setup process.
  • will present the used libraries and why we are using them.
  • will create the apps and explain the logic behind it.

I'll try to cover as many details as possible without boring you, but I still expect you to be familiar with some aspects of Python and Django.

the final version of the source code can be found at https://github.com/saad4software/alive-diary-backend

Series order

Check previous articles if interested!

  1. AI Project from Scratch, The Idea, Alive Diary
  2. Prove it is feasible with Google AI Studio
  3. Django API Project Setup (You are here 📍)

Start Project!

After installing Python, and setting up a virtual environment that suits your operating system. make sure to install those libraries

Django==4.2.16          # it is django itself!
django-cors-headers==4.4.0  # avoid cors-headers issues
django-filter==24.3     # easily filter text fields 
djangorestframework==3.15.2 # rest framework!
djangorestframework-simplejwt==5.3.1    # JWT token
pillow==10.4.0          # for images
python-dotenv==1.0.1        # load config from .env file
google-generativeai==0.7.2  # google api
ipython==8.18.1         # process gemini responses
django-parler==2.3              # multiple languages support
django-parler-rest==2.2         # multi-language with restframework
Enter fullscreen mode Exit fullscreen mode

requirements.txt

It doesn't have to be the same version though, depending on your Python version, you can install each one manually using

pip install django

or create the requirements file and use the same old

pip install -r requirements.txt

With django and the libraries installed, we can start our project

django-admin startproject alive_diary
cd alive_diary
python manage.py startapp app_account
python manage.py startapp app_admin
python manage.py startapp app_main
Enter fullscreen mode Exit fullscreen mode

We created a project called "alive_diary" and inside it, we created three apps,

  • app_account: for managing users' essential account data, registration, login, changing password, verifying account email, and similar responsibilities.
  • app_admin: for admin-related tasks, mainly managing users for this simple app
  • app_main: for the main app.

We will keep a minimum dependency among Django apps to make them reusable in other projects.

Settings

In short, this alive_diary/settings.py is the final settings file, let's walk rapidly through it

import os
from datetime import timedelta
from pathlib import Path
from dotenv import load_dotenv
Enter fullscreen mode Exit fullscreen mode

We have used timedelta from datetime package to set JWT lifetime, os and load_dotenv to load variables from the .env file.

load_dotenv()
Enter fullscreen mode Exit fullscreen mode

load variables from the .env file

BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.getenv("SECRET_KEY")
DEBUG = True
ALLOWED_HOSTS = ['*']
Enter fullscreen mode Exit fullscreen mode

added '*' for ALLOWED_HOSTS to allow connection from any IP. os.getenv get the key value from the .env file.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'rest_framework',
    'django_filters',
    'app_account',
    'app_admin',
    'app_main',
]
Enter fullscreen mode Exit fullscreen mode

Added the corsheaders, rest_framework, and django_filters apps, and our three apps, app_account, app_admin, and app_main.

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Enter fullscreen mode Exit fullscreen mode

Don't forget to add the CorsMiddleware middle ware before the CommonMiddleware

ROOT_URLCONF = 'alive_diary.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'alive_diary.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# CORS HEADERS
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
Enter fullscreen mode Exit fullscreen mode

adding cors headers config to the setting file

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}
Enter fullscreen mode Exit fullscreen mode

Use Simple JWT Authentication as default authentication class for rest framework library.

AUTH_USER_MODEL = 'app_account.User'
Enter fullscreen mode Exit fullscreen mode

change default user class to a custom one from app_account, we didn't create this model yet.

LANGUAGES = [
    ('en', 'English'),
    ('ar', 'Arabic')
]

STATICFILES_DIRS = [os.path.join(BASE_DIR, "app_main", "site_static")]
STATIC_ROOT = os.path.join(BASE_DIR, "app_main", "static")
MEDIA_ROOT = os.path.join(BASE_DIR, "app_main", "media")
MEDIA_URL = "/app_main/media/"

Enter fullscreen mode Exit fullscreen mode

Added supported languages, and set folders for files and statics

EMAIL_SENDER = os.getenv("EMAIL_SENDER")
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = os.getenv("EMAIL_HOST")
EMAIL_PORT = os.getenv("EMAIL_PORT")
EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD")
Enter fullscreen mode Exit fullscreen mode

Email settings, for email verification process. we are loading them from the .env file.

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(hours=8),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=5),
    'ROTATE_REFRESH_TOKENS': True,
    'BLACKLIST_AFTER_ROTATION': True,
    'UPDATE_LAST_LOGIN': False,

    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUDIENCE': None,
    'ISSUER': None,

    'AUTH_HEADER_TYPES': ('Bearer',),
    'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',

    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',

    'JTI_CLAIM': 'jti',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(days=1),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=3),
}
Enter fullscreen mode Exit fullscreen mode

Simple JWT token settings, we are setting the lifetime of access token "ACCESS_TOKEN_LIFETIME" to be 8 hours and the refresh token lifetime "REFRESH_TOKEN_LIFETIME" to be 5 days. we are rotating the refresh token (sending a new refresh token with every refresh token request) "ROTATE_REFRESH_TOKENS" and using 'Bearer' header prefix for authentication "AUTH_HEADER_TYPES".

The environment file

The used vars in the .env file should be

SECRET_KEY=django-insecure-8llc...
EMAIL_SENDER=emailer@s...
EMAIL_HOST=site...
EMAIL_PORT=587
EMAIL_HOST_USER=emailer@s...
EMAIL_HOST_PASSWORD=YN...
GOOGLE_API_KEY=AIz...
Enter fullscreen mode Exit fullscreen mode

.env

set the values according to your project, you can use the generated Django secret key for Secret Key, get the Google Gemini API key from AI studio, and use your email account for verification emails.
using a Google account to send emails is possible, but not recommended. the settings should be like

EMAIL_BACKEND = ‘django.core.mail.backends.smtp.EmailBackend’
EMAIL_HOST = ‘smtp.gmail.com’
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = ‘your_account@gmail.com’
EMAIL_HOST_PASSWORD = ‘your account’s password’
Enter fullscreen mode Exit fullscreen mode

and the user should enable "Less secure apps" to access gmail account. anyway, we can build the whole thing first, and worry about this later. just ignore the email verification part for now.

Conclude

Just to be able to run the project and finish this article, let's create a user model in app_account/models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass
Enter fullscreen mode Exit fullscreen mode

as simple as that! (we are going to work on it in the next article) let's make migrations and migrate

python manage.py makemigrations
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

if everything goes well, you should be able to run the project now by

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Please share any issues you have with me. We are ready to start working on the project apps now!

And that is it!

The next article should cover app_account, the user management app, it includes user management, login, register, change password, forgot password, account verification, and other user-related actions that we need in most apps.

Stay tuned 😎

Top comments (0)