Table of Contents
{{ poll.question }}
Home Backend Development Python Tutorial 以一个投票程序的实例来讲解Python的Django框架使用

以一个投票程序的实例来讲解Python的Django框架使用

Jun 10, 2016 pm 03:06 PM
django python vote

(一)关于Django

    Django是一个基于MVC构造的框架。但是在Django中,控制器接受用户输入的部分由框架自行处理,所以 Django 里更关注的是模型(Model)、模板(Template)和视图(Views),称为 MTV模式。

    Ubuntu下的安装:一般都自带Python的。网上教程比较多了....

dizzy@dizzy-pc:~$ python
Python 2.7.3 (default, Apr 20 2012, 22:44:07) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> help(django)
VERSION = (1, 6, 4, 'final', 0)
#可以查看django版本等信息。
Copy after login

(二)第一个Django的app

#环境:Python2.7,Django1.6,Ubuntu12.04
Python 及 Django 安装成功之后,就可以创建Django工程了

(1)教你开始写Django1.6的第1个app

#先创建一个文件夹
dizzy@dizzy-pc:~$ mkdir Python
dizzy@dizzy-pc:~$ cd Python
#然后创建工程
dizzy@dizzy-pc:~/Python$ django-admin.py startproject mysite
dizzy@dizzy-pc:~/Python$ cd mysite
#然后这个工程就可以启动服务了
dizzy@dizzy-pc:~/Python/mysite$ python manage.py runserver
Validating models...
 
0 errors found
July 23, 2014 - 14:17:29
Django version 1.6.4, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
#这样,打开浏览器访问: 便可看到: It Worked! 关闭服务:ctrl+c
 
#新创建的项目里面会有:manage.py文件,mysite文件夹
#在mysite文件夹里面会有:__init__.py,settings.py,urls.py,wsgi.py四个文件
 
#__init__.py是一个空文件,
#setting.py 是项目的配置文件。需要修改两个地方,这里使用默认的SQLite3数据库
LANGUAGE_CODE = 'zh-cn' #原:en-us
TIME_ZONE = 'Asia/Shanghai' #原:UTC
 
#配置完之后,便可以创建数据表了
dizzy@dizzy-pc:~/Python/mysite$ python manage.py syncdb
#创建是还要设置一个超级管理员,用于后台登录。
#设置完之后,开启服务,便可进入后台管理界面了:http://127.0.0.1:8000/admin/
Copy after login

(2)教你开始写Django1.6的第1个app


#创建一个用于投票的app。
#进入mysite工程根目录,创建app
dizzy@dizzy-pc:~/Python/mysite$ python manage.py startapp polls
dizzy@dizzy-pc:~/Python/mysite$ ls polls
admin.py  __init__.py  models.py urls.py  views.py
 
#这样。Django已经生成了,app通常所需的模板文件。
Copy after login

下面创建两个models。Poll 和 Choice

dizzy@dizzy-pc:~/Python/mysite$ vim polls/models.py
Copy after login

修改文件如下:

from django.db import models
 
# Create your models here.
 
from django.db import models
 
class Poll(models.Model):
  question = models.CharField(max_length=200)
  pub_date = models.DateTimeField('date published')
 
class Choice(models.Model):
  poll = models.ForeignKey(Poll)
  choice_text = models.CharField(max_length=200)
  votes = models.IntegerField(default=0)
#基本创建model过程就是这样,细节还要深入研究!
Copy after login

然后修改工程的配置文件setting.py,在INSTALLED_APP元组下面添加刚才创建的app:polls

dizzy@dizzy-pc:~/Python/mysite$ vim mysite/settings.py
 
INSTALLED_APPS = (
  'django.contrib.admin',
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.messages',
  'django.contrib.staticfiles',
  'polls',
)
 
#可以使用 python manage.py sql polls 查看app的建表SQL
#使用 python manage.py syncdb 进行创建数据库表
dizzy@dizzy-pc:~/Python/mysite$ ./manage.py sql polls
BEGIN;
CREATE TABLE "polls_poll" (
  "id" integer NOT NULL PRIMARY KEY,
  "question" varchar(200) NOT NULL,
  "pub_date" datetime NOT NULL
)
;
CREATE TABLE "polls_choice" (
  "id" integer NOT NULL PRIMARY KEY,
  "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id"),
  "choice_text" varchar(200) NOT NULL,
  "votes" integer NOT NULL
)
;
 
COMMIT;
 
#这样就可以通过设置model让Django自动创建数据库表了
    要想在后台admin中管理polls。还需要修改app下面的admin.py 文件。

from django.contrib import admin
 
# Register your models here.
 
from django.contrib import admin
from polls.models import Choice,Poll
 
class ChoiceInLine(admin.StackedInline):
  model = Choice
  extra = 3
 
class PollAdmin(admin.ModelAdmin):
  fieldsets = [
    (None,         {'fields':['question']}),
    ('Date information',  {'fields':['pub_date'],'classes':['collapse']}),
  ]
  inlines = [ChoiceInLine]
 
admin.site.register(Poll,PollAdmin)
 
#这部分代码,大体能看懂,具体的规则还要稍后的仔细研究。
##这部分代码,由于拼写失误,导致多处出错。细节决定成败!!

Copy after login


这样再重启服务,就能在后台管理polls应用了。

(3)视图和控制器部分

前面已经完成了model(M)的设置。剩下的只有view(V)和urls(C)了。Django的视图部分,由views.py 和 templates完成。

在polls中,我们将创建4个视图:

  • “index” 列表页 – 显示最新投票。
  • “detail” 投票页 – 显示一个投票的问题, 以及用户可用于投票的表单。
  • “results” 结果页 – 显示一个投票的结果。
  • 投票处理 – 对用户提交一个投票表单后的处理。

现在修改 views.py 创建用于视图的函数。

dizzy@dizzy-pc:~/Python/mysite$ vim polls/views.py

Copy after login

from django.shortcuts import render,get_object_or_404
 
# Create your views here.
from django.http import HttpResponse
from polls.models import Poll
 
def index(request):
  latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
  context = {'latest_poll_list':latest_poll_list}
  return render(request,'polls/index.html',context)
 
def detail(request,poll_id):
  poll = get_object_or_404(Poll,pk=poll_id)
  return render(request,'polls/detail.html',{'poll':poll})
 
def results(request,poll_id):
  return HttpResponse("you're looking at the results of poll %s." % poll_id)
 
def vote(request,poll_id):
  return HttpResponse("you're voting on poll %s." % poll_id)
 
#涉及Django的自带函数,不做深究。后面再做研究!
Copy after login

要想使试图能被访问,还要配置 urls.py 。mysite是整个网站的URLConf,但每个app可以有自己的URLConf,通过include的方式导入到根配置中即可。现在在polls下面新建 urls.py

from django.conf.urls import patterns,url
 
from polls import views
 
urlpatterns = patterns('',
  #ex:/polls/
  url(r'^$',views.index,name='index'),
  #ex:/polls/5/
  url(r'^(&#63;P<poll_id>\d+)/$',views.detail,name='detail'),
  #ex:/polls/5/results/
  url(r'^(&#63;P<poll_id>\d+)/results/$',views.results,name='results'),
  #ex:/polls/5/vote/
  url(r'^(&#63;P<poll_id>\d+)/vote/$',views.vote,name='vote'),
)
#url中,三个参数。正则的url,处理的函数,以及名称
#正则表达式!!!!!
Copy after login

然后在根 urls.py 文件中,include这个文件即可。

dizzy@dizzy-pc:~/Python/mysite$ vim mysite/urls.py

Copy after login

from django.conf.urls import patterns, include, url
 
from django.contrib import admin
admin.autodiscover()
 
urlpatterns = patterns('',
  # Examples:
  # url(r'^$', 'mysite.views.home', name='home'),
  # url(r'^blog/', include('blog.urls')),
 
  url(r'^polls/', include('polls.urls',namespace="polls")),
  url(r'^admin/', include(admin.site.urls)),
)
#有Example:两种形式。因为是元组,所以开始有“ ‘', ”。
Copy after login

然后开始创建模板文件。在polls下,创建templates文件夹。下面有index.html, detail.html 两个文件。

<!-- index.html -->
{% if latest_poll_list %}
  <ul>
  {% for poll in latest_poll_list %}
    <li><a href="{% url 'polls:detail' poll_id=poll.id %}">{{ poll.question }}</a></li>
  {% endfor %}
  </ul>
{% else %}
  <p>No polls are available.</p>
{% endif %}
 
<!--detail.html-->
<h1 id="poll-question">{{ poll.question }}</h1>
<ul>
{% for choice in poll.choice_set.all %}
  <li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
 
<!-- 视图设置完毕,具体语法还要深入研究! -->
<!-- 现在重启服务, 便可看到相应视图 -->
Copy after login

(4)投票功能完善

上面只是简单的实现了视图功能,并没有真正的实现投票功能。接下来就是完善功能。

#修改模板文件
dizzy@dizzy-pc:~/Python/mysite$ vim polls/templates/polls/detail.html
#需要加入form表单

<h1 id="poll-question">{{ poll.question }}</h1>
 
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
 
<form action="{% url 'polls:vote' poll.id %}" method="post">
{% csrf_token %}
{% for choice in poll.choice_set.all %}
  <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
  <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>

Copy after login

然后需要修改 views.py 中的 vote 处理函数。进行post数据的接收与处理。

# 文件 polls/views.py
 
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from polls.models import Choice, Poll
# ...
def vote(request, poll_id):
  p = get_object_or_404(Poll, pk=poll_id)
  try:
    selected_choice = p.choice_set.get(pk=request.POST['choice'])
  except (KeyError, Choice.DoesNotExist):
    # Redisplay the poll voting form.
    return render(request, 'polls/detail.html', {
      'poll': p,
      'error_message': "You didn't select a choice.",
    })
  else:
    selected_choice.votes += 1
    selected_choice.save()
    # Always return an HttpResponseRedirect after successfully dealing
    # with POST data. This prevents data from being posted twice if a
    # user hits the Back button.
    return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
Copy after login

在投票成功之后,让用户浏览器重定向到结果 results.html 页。

def results(request, poll_id):
  poll = get_object_or_404(Poll, pk=poll_id)
  return render(request, 'polls/results.html', {'poll': poll})
Copy after login

然后就需要创建模板 results.html 。


<!-- polls/templates/polls/results.html -->
 
<h1 id="poll-question">{{ poll.question }}</h1>
 
<ul>
{% for choice in poll.choice_set.all %}
  <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
 
<a href="{% url 'polls:detail' poll.id %}">Vote again&#63;</a>
Copy after login

            至此,重启服务就能看到单选按钮,以及submit了。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

See all articles