Introduction
This tutorial guides you through building a basic web application using Django and Django REST Framework (DRF). The application will manage a book collection, enabling CRUD (Create, Read, Update, Delete) operations via a REST API.
Prerequisites
venv
).Step 1: Environment Setup
Recommended VM Configuration:
VM Setup:
ubuntu-22.04-server-cloudimg-amd64.ova
image from a reliable source (like the official Ubuntu site).TMS_VM
).Ubuntu 22.04 Server Configuration:
Start the VM.
Log in and update the system: sudo apt update && sudo apt upgrade -y
Install essential tools: sudo apt install git python3 python3.10-venv python3-pip python3-venv git build-essential -y
Create a user: The following commands create a user named django
with appropriate permissions. Remember to replace "your_email@example.com"
with your actual email address.
<code class="language-bash">sudo groupadd bulletproof sudo adduser django sudo usermod -aG bulletproof django</code>
Create a project directory: mkdir /home/django/projects
Adjust group ownership and permissions:
<code class="language-bash">sudo chown :bulletproof /home/django/projects sudo chmod 775 /home/django/projects sudo usermod -d /home/django/projects django sudo chown django:bulletproof /home/django/projects su - django</code>
VS Code Setup (Remote-SSH):
Install the Python, Pylance, Flake8, Black, and Django extensions in VS Code. Ensure Flake8 and Black are also installed on the VM using pip. Configure VS Code to use the virtual environment's Python interpreter and enable linting and formatting. Create pyproject.toml
and .flake8
files for configuration (see examples in the original document).
Python Setup:
Create a virtual environment:
<code class="language-bash">mkdir tms && cd tms python3 -m venv .venv source .venv/bin/activate # (env\Scripts\activate on Windows)</code>
Install Django and DRF: pip install django djangorestframework
Create a Django project: django-admin startproject tms .
Run the development server: python manage.py runserver 0.0.0.0:8000
If you encounter a DisallowedHost
error, add your server's IP address to ALLOWED_HOSTS
in settings.py
.
Git Repository Setup:
README.md
, requirements.txt
(using pip freeze > requirements.txt
), LICENSE
, and .gitignore
files.ssh-keygen -t ed25519 -C "your_email@example.com"
. Add the public key to your GitHub account.git init
git remote add origin git@github.com:username/repository.git
git add .
, git commit -m "Initial commit"
, git push -u origin main
VM Snapshot:
Create a snapshot of your VM after the initial setup using VMware's snapshot functionality. Name it something descriptive, like "InitialSetup".
The above is the detailed content of Bulletproof Django API for a TMS project. For more information, please follow other related articles on the PHP Chinese website!