天天看點

Django2.2幫助文檔的第一個例子:一個簡易的投票系統—Prat1_2

原文連結

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

檢視Django版本

python -m Django --version
           

複制

本份教程使用的Django版本是2.2;Python版本是3.5或者之後(This tutorial is written for Django 2.2, which supports Python 3.5 and later.)

建立項目

django-admin startproject mysite
           

複制

建立app

python manage.py startapp polls
           

複制

在新生成的polls檔案夾下建立一個urls.py的檔案

寫上代碼

from django.urls import path
from . import views


urlpatterns = [
    path('',views.index,name="index")
]
           

複制

在目前目錄下的views.py檔案中寫入代碼

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index")
           

複制

在mysite目錄下的urls.py檔案裡寫入代碼

from django.urls import include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('polls/',include('polls.urls'))
]
           

複制

運作伺服器看下效果

python manager.py runserver
           

複制

在浏覽器裡輸入 http://127.0.0.1:8000/polls/ 可以看到

Django2.2幫助文檔的第一個例子:一個簡易的投票系統—Prat1_2

image.png

在mysite目錄下的settings檔案中的INSTALLED_APPS清單中寫入‘polls.apps.PollsConfig’

在polls檔案夾下的models.py檔案中寫入代碼

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question,on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
           

複制

在指令行視窗輸入

python manage.py migrate
python manage.py makemigrations polls
python manage.py sqlmigrate polls 0001
python manage.py migrate
           

複制

更改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 shell
from polls.models import Choice, Question
from django.utils import timezone
q = Question(question_text="What's new?", pub_date=timezone.now())
q.save()
q.question_text
q.pub_date
q.question_text = "What's up?"
q.save()
exit()
           

複制

建立管理者賬戶

python manage.py createsuperuser
Username: admin
Email address: [email protected]
Password: **********
Password (again): *********
Superuser created successfully.
python manage.py runserver
           

複制

Django2.2幫助文檔的第一個例子:一個簡易的投票系統—Prat1_2

image.png

至此,教程的part1和part2就重複出來了。重複過程中遇到了很多不懂的代碼,先不管了,争取把完整的教程重複完!