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!
- AI Project from Scratch, The Idea, Alive Diary
- Prove it is feasible with Google AI Studio
- 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!

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to solve the problem of Jieba word segmentation in scenic spot comment analysis? When we are conducting scenic spot comments and analysis, we often use the jieba word segmentation tool to process the text...

How to use regular expression to match the first closed tag and stop? When dealing with HTML or other markup languages, regular expressions are often required to...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version
SublimeText3 Linux latest version

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.