<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12

      django tutorial 都說了什么。

      新建項目及應用

      安裝虛擬環境和django

      pip install virtualenv
      

      新建虛擬環境并安裝django

      # 安裝依賴python3 的虛擬環境
      virtualenv djangovenv -p python3
      
      workon djangovenv
      # 安裝django
      pip install django
      

      新建項目和應用

      # 新建項目
      django-admin startproject mysite
      cd mysite
      # 新建應用
      python manage.py polls
      

      路由映射

      路由映射到基于函數的視圖---FBV

      • mysite/urls.py
      from django.urls import path, include
      
      urlpatterns = [
        path('polls/', include('polls.apps.PollsConfig'), name='polls')
      ]
      
      • polls/urls.py
      from django.urls import path
      from . import views
      
      app_name='polls'
      urlpatterns =[
        # 基于函數的視圖函數映射
        path('', views.index, name='index'),
        path('<int:question_id>/', views.detail, name='detail'),
        path('<int:question_id>/results/', views.results, name='results'),
        path('<int:question_id>/vote/', views.vote, name='vote'),
      ]
      

      視圖映射到基于類的視圖---CBV

      from django.urls import path
      from .import views
      
      app_name='polls'
      urlpatterns=[
        path('', views.IndexView.as_view(), name='index'),
        # 通過視圖類渲染的, id直接命名pk
        path('<int:pk>/', views.DetailView.as_view(), name='detail'),
        path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
        # vote沒有視圖模板, 所以不需要視圖類
        path('<int:question_id>/vote/', views.vote, name='vote'),
        
      

      視圖函數

      基于函數的視圖

      • polls/views.py 三種方法渲染視圖模板
      from django.shortcuts import render, get_object_or_404
      from django.url import request, HttpResponse
      from django.template import loader
      
      def index(request):
          latest_question_list = Question.objects.order_by('-pub_time')[:5]
          # 1. 直接文字顯示結果
          # output = ','.join([q.question_text for q in latest_question])
          # return HttpResponse(output)
      
          context = {
              'latest_question_list': latest_question_list
          }
          ## 2. 通過loader.template
          template = loader.template('polls/index.html')
          return HttpResponse(template.render(context, request))
          
          ## 3. 通過render函數渲染模板
          return render(request, 'polls/index.html, context)
      

      基于類的視圖

      Django封裝了不同類型的視圖類, 只需要填寫對應的屬性或改寫響應的方法就能自動渲染響應模板

      • views.py
      from django.views import generic
      
      def IndexView(generic.ListView):
        model = Question
        context_object_name='latest_question_list'
        template_name='polls/index.html'
      
        def get_queryset(self):
          return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]
      
      def DetailView(generic.DetailView):
        model = Question
        template_name='polls/detail.py'
      
        def get_queryset(self):
          # 過濾未來發布問題, 再測試中糾正的錯誤
          return Question.objects.filter(pub_date__lte=timezone.now()
      
      def ResultsView(generic.DetailView):
        model = Question
        template_name='polls/results.py'
      

      路由映射到類函數

      數據庫模型

      新建數據庫類

      • models.py
      from django.db import models
      from django.utils import timezone
      
      class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DatetimeField(default=timezone.now())
      
        def __str__(self):
          return self.question_text
      
        def was_published_recently(self):
          # 一天內發布的問題為近期問題, 注意未來的時間點不是近期,需要做分割
          return self.pub_date-datetime.delta(days=1) <= self.pub_date <= timezone.now()
      
      class Choice(models.Model):
        question = models.ForeignKey(Question, on_delete=models.CASCADE)
        choice_text = models.CharField(max_length=200)
        vote = models.IntegerField(default=0)
      
        def __str__(self):
          return self.choice_text
      
      • setting.py 中添加應用配置
      INSTALLED_APP=[
        'polls.apps.PollsConfig',
        ...
      ]
      
      • 命令行生成數據庫

      # 生成遷移文件
      python manage.py makemigrations polls
      # 執行遷移
      python manage.py migrate
      # 執行指定遷移
      python manage.py migrate polls 0001
      

      交互窗口操作數據庫

      python manage.py shell
      >>> from .models import Question, Choice
      >>> from django.utils import timezone
      >>> Question.objects.create(question_text='What's up?', pub_date=timezone.now())
      >>> q = question.objects.get(pk=1)
      >>> q.question_text
      >>> q.pub_date
      >>> q.id
      >>> q1 = Question(question_text='What's your favorate color?', pub_date=timezone.now())
      >>> q1.save()
      >>> Question.objects.all()
      >>> q.choice_set.all()
      >>> >>> q.choice_set.create(choice_text='Not much', votes=0)
      <Choice: Not much>
      >>> q.choice_set.create(choice_text='The sky', votes=0)
      <Choice: The sky>
      >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
      >>> c.question
      >>> Choice.objects.filter(question__pub_date__year=current_year)
      <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
      
      # Let's delete one of the choices. Use delete() for that.
      >>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
      >>> c.delete()
      

      視圖函數與模板

      編寫測試

      • TestCase類

      對數據庫模型類的實例方法的測試

      通過執行結果與期待的結果相同,則測試通過

      import datetime
      from django.test import TestCase
      from django.utils import timezone
      from .model import Question, Choice
      
      class QuestionTestCase(TestCase):
        """Question 模型單元測試"""
        def test_was_published_recently_with_future_question(self):
          # 測試未來的任務, 是否是最近的任務, 期待結果是False
          future_question = Question(pub_date=timezone.now()+datetime.timedelta(days=30))
          self.assertIs(future_question.was_published_recently, False)
      
        def test_was_published_recently_with_order_question(self):
          # 測試過去的任務(一天以上), 是否是最近的, 期待結果是False
          order_question = Question(pub_date=timezone.now()-datetime.timedelta(days=30))
          self.assertIs(order_question.was_published_recently, False)
      
        def test_was_published_recently_with_recently_quesiton(self):
          # 測試一天內的任務是否為最近任務, 期待結果為True
          recently_question = Question(pub_date=timezone.now()-datetime.timedelta(hours=23,minutes=59,seconds=59)
          self.assertIs(recently_question.was_published_recently, True)
        ## 通過以上的三個測試通過,對應選項, 可以判定哪個區間出了問題, 來修補漏洞
      

      對視圖函數測試響應結果數據

      def create_question(question_text, days):
        # 與之前的創建實例不同, 這個需要寫入測試臨時數據庫中
        time = timezone.now() + datetime.timedelta(days=days)
        return Question.objects.create(question_text=question_text, pub_date=pub_date)
      
      class QuestionIndexViewTestCase(TestCase):
         def test_no_question(self):
          # 測試沒有發布問題 期待 訪問成功, 響應包含為 "No Polls.." queryset為[]
          response = self.client.get(reverse('polls:index'))
          self.assertEqual(response.status_code, 200) # 測試訪問狀態碼, 連接成功
          self.assertContains(response, 'No polls')
          self.assertQuerysetEqual(response.context['latest_question_list'], [])
      
        def test_past_question(self):
          # 測試過去發布問題, 期待queryset中包含[question]
          question = create_quesiton("Past question", days=-30)
          response = self.client.get(reverse('polls:index'))
          self.assertQuerysetEqual(response.context['latest_question_list'], [question])
      
        def test_future_question(self):
          # 測試未來時間發布問題, 期待queryset為[]
          question = create_quesiton("Future question", days=30)
          response = self.client.get(reverse('polls:index'))
          self.assertQuerysetEqual(response.context['latest_question_list'], [])
      
        def test_past_question_and_future_question(self):
          # 測試過去發布問題, 期待queryset中包含[question]
          question = create_question("Past question", days=-30)
          create_question("Future question", days=30)
          response = self.client.get(reverse('polls:index'))
          self.assertQuerysetEqual(response.context['latest_question_list'], [question])
      
        def test_two_past_questions(self):
          # 測試過去發布問題, 期待queryset中包含[question1, question2]
          question1 = create_quesiton("Past question 1.", days=-30)
          question2 = create_quesiton("Past question 2.", days=-5)
          response = self.client.get(reverse('polls:index'))
          self.assertQuerysetEqual(response.context['latest_question_list'], [question2, question1])
      
      
      class QuestionDetailViewTestCase(TestCase):
          # 測試過去發布問題, 期待結果中包含對應問題
          def test_past_question(self):
              question = create_question(question_text="Past question", days=-5)
              response = self.client.get(reverse('polls:detail', args=(question.id,)))
              self.assertContains(response, question.question_text)
          # 測試未來發布問題, 期待結果訪問結果未找到 404
          def test_future_question(self):
              question = create_question(question_text="Future question", days=5)
              response = self.client.get(reverse('polls:detail', args=(question.id,)))
              self.assertEqual(response.status_code, 404)
      
      

      后臺模板渲染

      posted @ 2022-03-26 23:58  lghgo  閱讀(63)  評論(0)    收藏  舉報
      主站蜘蛛池模板: 成人亚洲狠狠一二三四区| 亚洲香蕉免费有线视频| 日韩中文字幕精品人妻| 亚洲色大成网站www在线| 欧美大胆老熟妇乱子伦视频| 麻豆国产高清精品国在线| 国产特级毛片aaaaaa毛片| 中文字幕日韩精品有码| 国产精品久久精品国产| 九九色这里只有精品国产| 成人午夜激情在线观看| 久久国产精品日本波多野结衣| 强奷乱码中文字幕| 特黄 做受又硬又粗又大视频| 国产成人高清精品亚洲一区| 欧美人妻在线一区二区| 国产精品成人自产拍在线| 国产精品天天看天天狠| 亚洲日本欧美日韩中文字幕| 亚洲国产色婷婷久久99精品91| 亚洲岛国成人免费av| 天天夜碰日日摸日日澡性色av | 国产三级国产精品国产专区| 天天做天天爱夜夜爽女人爽| 亚洲高清免费在线观看| 福利一区二区不卡国产| 天天爽夜夜爱| 伊人久久大香线蕉综合影院| 国产一区二区三区内射高清| 被灌满精子的少妇视频| 在线视频一区二区三区色| 国产精品三级在线观看无码| 国产午夜福利在线观看播放| 无码帝国www无码专区色综合| 亚洲成av一区二区三区| 亚洲AV成人片在线观看| 免费观看的av在线播放| 婷婷久久香蕉五月综合加勒比 | 久久99热只有频精品8| 老子午夜精品无码| 精品一区二区亚洲国产|