Django API Project Setup

Mary-Kate Olsen
Release: 2024-10-28 19:04:29
Original
751 people have browsed it

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
Copy after login
Copy after login

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
Copy after login
Copy after login

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
Copy after login
Copy after login

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

load_dotenv()
Copy after login
Copy after login

load variables from the .env file

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

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',
]
Copy after login
Copy after login

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',
]
Copy after login
Copy after login

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
Copy after login
Copy after login

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
Copy after login
Copy after login

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
Copy after login
Copy after login

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

load_dotenv()
Copy after login
Copy after login

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 = ['*']
Copy after login
Copy after login

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',
]
Copy after login
Copy after login

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',
]
Copy after login
Copy after login

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
Copy after login

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',
    ],
}
Copy after login

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'
Copy after login

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

Copy after login

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!

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!