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
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
Check previous articles if interested!
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,
We will keep a minimum dependency among Django apps to make them reusable in other projects.
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 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.
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!
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!