Django2.2帮助文档的第一个例子:一个简易的投票系统—Prat3_4

原文链接

https://docs.djangoproject.com/en/2.2/intro/tutorial01/

强烈推荐
  • b站教学视频 Django 2.0和Python快速入门 (更新完毕) 强烈推荐
开始搭建简易投票系统
  • 创建项目
django-admin startproject mysite  
  • 创建app
cd mysite  django-admin startapp polls  
  • 在polls文件夹下新建一个urls.py,写上如下代码
from django.urls import path  from . import views      urlpatterns = [      path('',views.index,name='index'),  ]  
  • 在mysite文件夹下的urls.py文件夹下写上代码
from django.contrib import admin  from django.urls import path  from django.urls import include    urlpatterns = [      path('admin/', admin.site.urls),      path('polls/',include('polls.urls')),  ]  
  • 在polls文件夹下新建一个templates文件夹
  • 在templates文件夹下新建一个index.html文件,在文件里写些内容
<!DOCTYPE html>  <html lang="en">  <head>      <meta charset="UTF-8">      <title>这是index页面</title>  </head>  <body>  <h1>这是index页面</h1>  </body>  </html>  
  • 在mysite文件夹下的settings.py文件中添加模板文件夹的路径
os.path.join(BASE_DIR,'polls/templates')  
  • 在polls文件夹下的views.py文件中添加代码
from django.shortcuts import render    # Create your views here.    def index(request):      return render(request,'index.html')  
  • 试着运行服务器
python manage.py runserver  

返回结果

image.png

  • 注册app,在mysite文件夹下的settings.py文件中写入
INSTALLED_APPS = [      'django.contrib.admin',      'django.contrib.auth',      'django.contrib.contenttypes',      'django.contrib.sessions',      'django.contrib.messages',      'django.contrib.staticfiles',      'polls.apps.PollsConfig',  ]  
  • 在polls文件夹下的models.py文件中写入如下代码
import datetime  from django.db import models  from django.utils import timezone  # Create your models here.    class Question(models.Model):      question_text = models.CharField(max_length=200)      pub_date = models.DateTimeField('date published')        def __str__(self):          return self.question_text        def was_published_recently(self):          return self.pub_date >= timezone.now() - datetime.timedelta(days=1)      class Choice(models.Model):      question = models.ForeignKey(Question,on_delete = models.CASCADE)      choice_text = models.CharField(max_length=200)      votes = models.IntegerField(default=0)        def __str__(self):          return self.choice_text  
  • 迁移数据库
python manage.py makemigrations polls  python manage.py sqlmigrate polls 0001  python manage.py migrate  
  • 用shell添加问题
from polls.models import Choice, Question  Question.objects.all()  from django.utils import timezone  q = Question(question_text="你的性别是?", pub_date=timezone.now())  q.save()  q.choice_set.create(choice_text='男', votes=0)  q.choice_set.create(choice_text='女', votes=0)  q.choice_set.create(choice_text='不告诉你', votes=0)  q = Question(question_text="你喜欢的运动是?", pub_date=timezone.now())  q.choice_set.create(choice_text='篮球', votes=0)  q.choice_set.create(choice_text='足球', votes=0)  q.choice_set.create(choice_text='排球', votes=0)  q.choice_set.create(choice_text='不告诉你', votes=0)  Question.objects.all()  Choice.objects.all()  
  • 创建超级管理员用户
python manage.py createsuperuser  

依次输入用户名,邮箱,密码

  • 运行服务器
python manage.py runserver  

访问 http://127.0.0.1:8000/admin/ 结果

image.png

  • 在polls文件夹下的admin.py文件中添加
from django.contrib import admin    # Register your models here.      from .models import Question    admin.site.register(Question)  

刷新,重新访问http://127.0.0.1:8000/admin/

结果

image.png

image.png

  • 更改views.py文件中的代码
from django.shortcuts import render  from django.shortcuts import get_object_or_404  from .models import Question    # Create your views here.    def index(request):      latest_question_list = Question.objects.order_by('-pub_date')[:5]      context = {"latest_question_list":latest_question_list}      return render(request,'index.html',context= context)    def detail(request,question_id):      question = get_object_or_404(Question,pk=question_id)      return render(request,'detail.html',context={'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"),  ]  
  • 更改index.html文件中的代码
<!DOCTYPE html>  <html lang="en">  <head>      <meta charset="UTF-8">      <title>这是index页面</title>  </head>  <body>  <h1>这是index页面</h1>  {% if latest_question_list %}      <ul>          {% for question in latest_question_list %}              <li><a href="{{ question.id }}">{{ question.question_text }}</a></li>          {% endfor %}      </ul>  {% else %}      <p>No polls are available.</p>  {% endif %}  </body>  </html>  
  • 在templates文件夹下新建文件detail.html
<!DOCTYPE html>  <html lang="en">  <head>      <meta charset="UTF-8">      <title>这是详情页面</title>  </head>  <body>  <h1>这是详情页面</h1>  <h2>{{ question.question_text }}</h2>  <ul>  {% for choice in question.choice_set.all %}      <li>{{ choice.choice_text }}</li>  {% endfor %}  </ul>  </body>  </html>  

结果

image.png

image.png

  • 在polls文件夹下新建static文件夹,然后在这个文件夹下新建style.css文件
li a {      color:green  }  
  • 最终代码 index.html
<!DOCTYPE html>  <html lang="en">  <head>      <meta charset="UTF-8">      <title>这是index页面</title>  </head>  <body>  {% load static %}  <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}">  <h1>这是index页面</h1>  {% if latest_question_list %}      <ul>          {% for question in latest_question_list %}              <li><a href="{{ question.id }}">{{ question.question_text }}</a></li>          {% endfor %}      </ul>  {% else %}      <p>No polls are available.</p>  {% endif %}  </body>  </html>  

detail.html

<!DOCTYPE html>  <html lang="en">  <head>      <meta charset="UTF-8">      <title>这是详情页面</title>  </head>  <body>  <h1>这是详情页面</h1>  <h2>{{ question.question_text }}</h2>  {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}    <form action="{% url 'vote' question.id %}" method="post">      {% csrf_token %}      {% for choice in question.choice_set.all %}          <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">          <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</labelfor>      {% endfor %}      <input type="submit" value="Vote">  </form>  <ul>  {% for choice in question.choice_set.all %}      <li>{{ choice.choice_text }}</li>  {% endfor %}  </ul>  </body>  </html>  

results.html

<!DOCTYPE html>  <html lang="en">  <head>      <meta charset="UTF-8">      <title>这是结果页面</title>  </head>  <body>  <h1>{{ question.question_text }}</h1>  <ul>      {% for choice in question.choice_set.all %}      <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize}}</li>      {% endfor %}  </ul>  <a href="{% url 'detail' question.id %}"> Vote again ?</a>  </body>  </html>  

urls.py

from django.urls import path  from . import views      urlpatterns = [      path('',views.index,name='index'),      path('<int:question_id>/',views.detail,name="detail"),      path('<int:question_id>/vote/',views.vote,name='vote'),      path('<int:question_id>/results/',views.results,name="results"),  ]  

views.py

from django.shortcuts import render  from django.shortcuts import get_object_or_404  from django.http import Http404  from django.http import HttpResponseRedirect  from django.urls import reverse  from .models import Question      # Create your views here.    def index(request):      latest_question_list = Question.objects.order_by('-pub_date')[:5]      context = {"latest_question_list":latest_question_list}      return render(request,'index.html',context= context)    def detail(request,question_id):      try:          question = get_object_or_404(Question,pk=question_id)      except Question.DoesNotExist:          raise Http404("Question does not exist!")      return render(request,'detail.html',context={'question':question})    def vote(request,question_id):      question = get_object_or_404(Question,pk=question_id)      try:          selected_choice = question.choice_set.get(pk=request.POST['choice'])      except (KeyError,choice.DoesNotExist):          return render(request,'detail.html',context={'question':question,                                                       'error_message':"You did not select a choice!"})      else:          selected_choice.votes += 1          selected_choice.save()          return HttpResponseRedirect(reverse('results',args=(question_id,)))    def results(request,question_id):      question = get_object_or_404(Question,pk=question_id)      return render(request,'results.html',context={'question':question})  

model.py

import datetime  from django.db import models  from django.utils import timezone  # Create your models here.    class Question(models.Model):      question_text = models.CharField(max_length=200)      pub_date = models.DateTimeField('date published')        def __str__(self):          return self.question_text        def was_published_recently(self):          return self.pub_date >= timezone.now() - datetime.timedelta(days=1)      class Choice(models.Model):      question = models.ForeignKey(Question,on_delete = models.CASCADE)      choice_text = models.CharField(max_length=200)      votes = models.IntegerField(default=0)        def __str__(self):          return self.choice_text  
  • 最终效果

image.png

image.png

image.png

image.png

image.png

至此这个例子就重复完了!