Python 写 web 第二步:在项目中新建应用

通过不同的应用来完善项目的各种功能,一个项目可以表示一个项目的一种或多种功能。

1.进入mysite文件夹,在cmd窗口输入指令

pythonmanage.py startapp polls

Python 写 web 第二步:在项目中新建应用

创建一个名叫polls的投票应用,可以在根目录中看到多了一个文件

Python 写 web 第二步:在项目中新建应用

2.然后打开polls文件夹,用sublime打卡views.py文件添加如下代码

fromdjango.shortcuts import render

from django.httpimport HttpResponse

defindex(request):

    returnHttpResponse("Hello, world. You're at the polls index.")

Python 写 web 第二步:在项目中新建应用

3.接着在polls文件新建一个urls.py文件,添加如下代码:

fromdjango.conf.urls import url

from . importviews

urlpatterns =[

    url(r'^$', views.index, name='index'),              

]

Python 写 web 第二步:在项目中新建应用

4.再修改mysite文件中的urls.py文件:

fromdjango.conf.urls import url, include

fromdjango.contrib import admin

urlpatterns =[

    url(r'^admin/', admin.site.urls),

    url(r'^polls/', include('polls.urls')),

]

Python 写 web 第二步:在项目中新建应用

5.最后启动服务器: python manage.py runserver

进入网址:http://127.0.0.1:8000/polls/ 就可以看到

Python 写 web 第二步:在项目中新建应用

polls 文件夹下的views.py文件return返回的内容一致

Python 写 web 第二步:在项目中新建应用

6.几个注意的点:(url代表地址的映射问题)

Python 写 web 第二步:在项目中新建应用

Python 写 web 第二步:在项目中新建应用

Python 写 web 第二步:在项目中新建应用

Python 写 web 第二步:在项目中新建应用

7.打开polls文件下的models.py文件加入如下代码

fromdjango.db import models

# Create yourmodels here.

classQuestion(models.Model):

    question_text =models.CharField(max_length=200)

    pub_date = models.DateTimeField('datepublished')

    def __str__(self):

        return self.question_text

Python 写 web 第二步:在项目中新建应用

8.接着在mysite文件夹下的settings.py文件,在39行加入

   'polls.apps.PollsConfig', 

Python 写 web 第二步:在项目中新建应用

9.然后再cmd窗口执行数据迁移命令,修改数据库

pythonmanage.py makemigrations

Python 写 web 第二步:在项目中新建应用

python manage.pymigrate

Python 写 web 第二步:在项目中新建应用

然后在Navicat中可以看到我们新建了一张表

Python 写 web 第二步:在项目中新建应用

这两个字段对应models.py中的两个字段

Python 写 web 第二步:在项目中新建应用

字符类型也相对应

Python 写 web 第二步:在项目中新建应用

10.再打开polls文件夹下的admin.py添加代码

from .modelsimport Question

admin.site.register(Question)

Python 写 web 第二步:在项目中新建应用

最后运行服务器:python manage.py runserver

浏览器进入http://127.0.0.1:8000/admin/

Python 写 web 第二步:在项目中新建应用

Python 写 web 第二步:在项目中新建应用

最多只能添加200字符,与设定相符

Python 写 web 第二步:在项目中新建应用

这样就完成了投票系统中的设置问题编写过程,接下来是编写投票的过程。