Django 项目教程
1. 项目的目录结构及介绍
Django 项目的目录结构通常包含以下几个主要部分:
django/
: 这是 Django 项目的主目录,包含了所有的源代码和资源文件。docs/
: 包含项目的文档文件,如安装指南、教程等。tests/
: 包含项目的测试代码。django/bin/
: 包含一些可执行文件,如django-admin.py
。django/conf/
: 包含项目的配置文件。django/contrib/
: 包含一些内置的应用程序,如admin
和auth
。django/db/
: 包含数据库相关的代码。django/forms/
: 包含表单相关的代码。django/middleware/
: 包含中间件相关的代码。django/template/
: 包含模板引擎相关的代码。django/urls/
: 包含 URL 路由相关的代码。django/views/
: 包含视图函数和类。
2. 项目的启动文件介绍
Django 项目的启动文件通常是 manage.py
,它位于项目的根目录下。manage.py
是一个命令行工具,用于与 Django 项目进行交互,可以执行诸如启动开发服务器、创建应用、迁移数据库等操作。
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
3. 项目的配置文件介绍
Django 项目的主要配置文件是 settings.py
,它通常位于项目的 myproject/
目录下。这个文件包含了项目的所有配置选项,如数据库配置、静态文件路径、中间件配置等。
"""
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 3.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'your-secret-key'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'myproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS':