python:chapter36

第三十六章: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)
# 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项目

下一章:第三十七章:网络爬虫实战

该主题尚不存在

您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。

  • python/chapter36.txt
  • 最后更改: 2026/04/09 14:42
  • 张叶安