search

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

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

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 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

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

load_dotenv()

load variables from the .env file

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

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',
]

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',
]

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

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

adding cors headers config to the setting file

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

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

import os
from datetime import timedelta
from pathlib import Path
from dotenv import load_dotenv

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

load_dotenv()

Added supported languages, and set folders for files and statics

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

Email settings, for email verification process. we are loading them 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',
]

Simple JWT token settings, we are setting the lifetime of access token "ACCESS_TOKEN_LIFETIME" to be 8 hours and refresh token lifetime "REFRESH_TOKEN_LIFETIME" to be 5 days. we are rotating the refresh token (sending 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

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',
]

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

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

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

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}

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

AUTH_USER_MODEL = 'app_account.User'

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

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/"

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

And that is it!

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 ?

The above is the detailed content of Django API Project Setup. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the performance differences in element-wise operations between lists and arrays.Explain the performance differences in element-wise operations between lists and arrays.May 06, 2025 am 12:15 AM

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

How can you perform mathematical operations on entire NumPy arrays efficiently?How can you perform mathematical operations on entire NumPy arrays efficiently?May 06, 2025 am 12:15 AM

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

How do you insert elements into a Python array?How do you insert elements into a Python array?May 06, 2025 am 12:14 AM

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

How can you make a Python script executable on both Unix and Windows?How can you make a Python script executable on both Unix and Windows?May 06, 2025 am 12:13 AM

TomakeaPythonscriptexecutableonbothUnixandWindows:1)Addashebangline(#!/usr/bin/envpython3)andusechmod xtomakeitexecutableonUnix.2)OnWindows,ensurePythonisinstalledandassociatedwith.pyfiles,oruseabatchfile(run.bat)torunthescript.

What should you check if you get a 'command not found' error when trying to run a script?What should you check if you get a 'command not found' error when trying to run a script?May 06, 2025 am 12:03 AM

When encountering a "commandnotfound" error, the following points should be checked: 1. Confirm that the script exists and the path is correct; 2. Check file permissions and use chmod to add execution permissions if necessary; 3. Make sure the script interpreter is installed and in PATH; 4. Verify that the shebang line at the beginning of the script is correct. Doing so can effectively solve the script operation problem and ensure the coding process is smooth.

Why are arrays generally more memory-efficient than lists for storing numerical data?Why are arrays generally more memory-efficient than lists for storing numerical data?May 05, 2025 am 12:15 AM

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

How can you convert a Python list to a Python array?How can you convert a Python list to a Python array?May 05, 2025 am 12:10 AM

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Can you store different data types in the same Python list? Give an example.Can you store different data types in the same Python list? Give an example.May 05, 2025 am 12:10 AM

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools