第三十六章:Django Web开发
本章目标
完成本章学习后,你将能够:
- 创建Django项目
- 定义模型和视图
- 使用Admin后台
- 开发完整应用
快速开始
```bash # 安装 pip install django
# 创建项目 django-admin startproject mysite
# 创建应用 python manage.py startapp polls ```
模型定义
# polls/models.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
视图和URL
# polls/views.py from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from .models import Question def index(request): latest = Question.objects.order_by('-pub_date')[:5] return render(request, 'polls/index.html', {'latest': latest}) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question})
# polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), ]
本章练习
1. 创建完整的Django应用 2. 使用Django REST Framework 3. 部署Django项目
下一章:第三十七章:网络爬虫实战