当然,以下是一个完整的Django项目的整体框架,包括项目目录结构、关键文件和各自的作用。这个框架假设你有一个名为 myproject
的项目,以及一个名为 myapp
的应用。
目录结构
myproject/
│
├── manage.py
├── myproject/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── asgi.py
│ └── wsgi.py
│
├── myapp/
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── forms.py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ ├── views.py
│ ├── templates/
│ │ └── myapp/
│ │ ├── base.html
│ │ ├── index.html
│ │ ├── contact.html
│ └── static/
│ └── myapp/
│ ├── css/
│ ├── js/
│ └── images/
│
├── templates/
│ └── registration/
│ └── login.html
│
└── static/
├── css/
├── js/
└── images/
关键文件和作用
项目级别
manage.py
: Django项目的命令行工具,可以用来运行服务器、创建应用、数据库迁移等。myproject/
:
__init__.py
: 标识这是一个Python包。settings.py
: 项目的配置文件,包含数据库配置、静态文件配置等。urls.py
: 项目的URL路由配置文件。asgi.py
: 项目ASGI应用的入口。wsgi.py
: 项目WSGI应用的入口。
应用级别
myapp/
:
__init__.py
: 标识这是一个Python包。admin.py
: Django管理后台的配置文件。apps.py
: 应用的配置文件。forms.py
: 应用的表单定义。models.py
: 应用的数据模型定义。tests.py
: 应用的测试用例。urls.py
: 应用的URL路由配置文件。views.py
: 应用的视图定义。templates/myapp/
: 应用的模板文件。
base.html
: 基础模板。index.html
: 主页模板。contact.html
: 联系表单模板。
static/myapp/
: 应用的静态文件(CSS、JavaScript、图片等)。
示例文件内容
settings.py
# myproject/settings.py
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'your-secret-key'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
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': [os.path.join(BASE_DIR, 'templates')],
'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 = 'myproject.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/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
urls.py
(项目级别)
# myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
urls.py
(应用级别)
# myapp/urls.py
from django.urls import path
from .views import index_view, contact_view
urlpatterns = [
path('', index_view, name='index'),
path('contact/', contact_view, name='contact'),
]
views.py
# myapp/views.py
from django.shortcuts import render
from .forms import ContactForm
def index_view(request):
return render(request, 'myapp/index.html')
def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# 处理表单数据
return redirect('index')
else:
form = ContactForm()
return render(request, 'myapp/contact.html', {'form': form})
forms.py
# myapp/forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
models.py
# myapp/models.py
from django.db import models
class Contact(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
message = models.TextField()
def __str__(self):
return self.name
templates/myapp/index.html
<!-- templates/myapp/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<a href="{% url 'contact' %}">Contact Us</a>
</body>
</html>
templates/myapp/contact.html
<!-- templates/myapp/contact.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact</title>
</head>
<body>
<h1>Contact Us</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</body>
</html>
这个完整的Django项目框架展示了如何组织和配置你的项目文件夹、关键文件及其内容,使得项目清晰、有条理,并且容易维护和扩展。