Django是“电池齐全”的Web框架,提供ORM、认证、管理后台等完整功能,适合构建大型企业级应用。其MTV模式(Model-Template-View)与约定优于配置原则大幅提高开发效率。
Django项目结构详解
mysite/
├── manage.py
├── mysite/
│ ├── __init__.py
│ ├── settings.py # 配置文件
│ ├── urls.py # URL路由
│ ├── asgi.py # ASGI入口
│ └── wsgi.py # WSGI入口
├── app/
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── models.py # 数据模型
│ ├── views.py # 视图函数
│ ├── urls.py # 应用路由
│ └── templates/
│ └── app/
│ └── index.html
└── static/
创建应用:
python manage.py startapp blog
在settings.py中注册应用:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog', # 新增应用
]
⚙️ 开发服务器: `python manage.py runserver 0.0.0.0:8000`
模型(Model)设计
Django ORM支持丰富字段类型:
- 文本: CharField、TextField
- 数字: IntegerField、DecimalField、FloatField
- 日期时间: DateField、DateTimeField
- 关系: ForeignKey、OneToOneField、ManyToManyField
- 文件: FileField、ImageField
模型定义示例:
from django.db import models
from django.contrib.auth.models import User
class Article(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField('Tag', blank=True)
is_published = models.BooleanField(default=False)
class Meta:
ordering = ['-created_at']
verbose_name = '文章'
verbose_name_plural = '文章列表'
def __str__(self):
return self.title
关系字段说明:
on_delete=models.CASCADE:级联删除
on_delete=models.PROTECT:禁止删除
on_delete=models.SET_NULL:设为NULL(需blank=True)
related_name='articles':反向查询名
视图(View)开发
Django提供两种视图类型:
- 函数视图(FBV): 简单直接
- 类视图(CBV): 复用性高,支持继承
函数视图示例:
from django.shortcuts import render, get_object_or_404
from .models import Article
def article_list(request):
articles = Article.objects.filter(is_published=True)
return render(request, 'blog/article_list.html', {'articles': articles})
def article_detail(request, pk):
article = get_object_or_404(Article, pk=pk, is_published=True)
return render(request, 'blog/article_detail.html', {'article': article})
类视图示例:
from django.views.generic import ListView, DetailView
from .models import Article
class ArticleListView(ListView):
model = Article
template_name = 'blog/article_list.html'
context_object_name = 'articles'
def get_queryset(self):
return Article.objects.filter(is_published=True)
class ArticleDetailView(DetailView):
model = Article
template_name = 'blog/article_detail.html'
def get_object(self):
return get_object_or_404(
Article,
pk=self.kwargs['pk'],
is_published=True
)
⚡ 性能优化: 使用`select_related`(外键)和`prefetch_related`(多对多)减少数据库查询次数。
管理后台(Admin)定制
注册模型到管理后台:
# admin.py
from django.contrib import admin
from .models import Article, Tag
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'created_at', 'is_published')
list_filter = ('is_published', 'created_at', 'author')
search_fields = ('title', 'content')
date_hierarchy = 'created_at'
ordering = ('-created_at',)
filter_horizontal = ('tags',)
@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
list_display = ('name', 'slug')
prepopulated_fields = {'slug': ('name',)}
常用Admin功能:
list_display:列表页显示字段
list_filter:右侧过滤器
search_fields:顶部搜索框
fieldsets:表单分组
readonly_fields:只读字段
表单(Form)处理
创建表单类:
from django import forms
from .models import Comment
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['content']
widgets = {
'content': forms.Textarea(attrs={
'rows': 4,
'placeholder': '请输入评论内容...'
})
}
在视图中使用:
def add_comment(request, article_id):
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.article_id = article_id
comment.save()
return redirect('article_detail', pk=article_id)
else:
form = CommentForm()
return render(request, 'blog/add_comment.html', {'form': form})
模板渲染:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">提交评论</button>
</form>