国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

以一個投票程序的實例來講解Python的Django框架使用

2020-01-04 17:43:21
字體:
供稿:網(wǎng)友
這篇文章主要介紹了以一個投票程序的實例來講解Python的Django框架使用,Django是Python世界中人氣最高的MVC框架,需要的朋友可以參考下
 

(一)關(guān)于Django

    Django是一個基于MVC構(gòu)造的框架。但是在Django中,控制器接受用戶輸入的部分由框架自行處理,所以 Django 里更關(guān)注的是模型(Model)、模板(Template)和視圖(Views),稱為 MTV模式。

    Ubuntu下的安裝:一般都自帶Python的。網(wǎng)上教程比較多了....

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

(二)第一個Django的app

#環(huán)境:Python2.7,Django1.6,Ubuntu12.04
        Python 及 Django 安裝成功之后,就可以創(chuàng)建Django工程了       

    (1)教你開始寫Django1.6的第1個app

#先創(chuàng)建一個文件夾dizzy@dizzy-pc:~$ mkdir Pythondizzy@dizzy-pc:~$ cd Python#然后創(chuàng)建工程dizzy@dizzy-pc:~/Python$ django-admin.py startproject mysitedizzy@dizzy-pc:~/Python$ cd mysite#然后這個工程就可以啟動服務(wù)了dizzy@dizzy-pc:~/Python/mysite$ python manage.py runserverValidating models... 0 errors foundJuly 23, 2014 - 14:17:29Django 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! 關(guān)閉服務(wù):ctrl+c #新創(chuàng)建的項目里面會有:manage.py文件,mysite文件夾#在mysite文件夾里面會有:__init__.py,settings.py,urls.py,wsgi.py四個文件 #__init__.py是一個空文件,#setting.py 是項目的配置文件。需要修改兩個地方,這里使用默認的SQLite3數(shù)據(jù)庫LANGUAGE_CODE = 'zh-cn' #原:en-usTIME_ZONE = 'Asia/Shanghai' #原:UTC #配置完之后,便可以創(chuàng)建數(shù)據(jù)表了dizzy@dizzy-pc:~/Python/mysite$ python manage.py syncdb#創(chuàng)建是還要設(shè)置一個超級管理員,用于后臺登錄。#設(shè)置完之后,開啟服務(wù),便可進入后臺管理界面了:http://127.0.0.1:8000/admin/

    (2)教你開始寫Django1.6的第1個app

 

#創(chuàng)建一個用于投票的app。#進入mysite工程根目錄,創(chuàng)建appdizzy@dizzy-pc:~/Python/mysite$ python manage.py startapp pollsdizzy@dizzy-pc:~/Python/mysite$ ls pollsadmin.py  __init__.py  models.py urls.py  views.py #這樣。Django已經(jīng)生成了,app通常所需的模板文件。

        下面創(chuàng)建兩個models。Poll 和 Choice

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

        修改文件如下:

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)#基本創(chuàng)建model過程就是這樣,細節(jié)還要深入研究!

        然后修改工程的配置文件setting.py,在INSTALLED_APP元組下面添加剛才創(chuàng)建的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 進行創(chuàng)建數(shù)據(jù)庫表dizzy@dizzy-pc:~/Python/mysite$ ./manage.py sql pollsBEGIN;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; #這樣就可以通過設(shè)置model讓Django自動創(chuàng)建數(shù)據(jù)庫表了    要想在后臺admin中管理polls。還需要修改app下面的admin.py 文件。from django.contrib import admin # Register your models here. from django.contrib import adminfrom 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) #這部分代碼,大體能看懂,具體的規(guī)則還要稍后的仔細研究。##這部分代碼,由于拼寫失誤,導(dǎo)致多處出錯。細節(jié)決定成敗!!

 

        這樣再重啟服務(wù),就能在后臺管理polls應(yīng)用了。

(3)視圖和控制器部分

            前面已經(jīng)完成了model(M)的設(shè)置。剩下的只有view(V)和urls(C)了。Django的視圖部分,由views.py 和 templates完成。

            在polls中,我們將創(chuàng)建4個視圖:

  • “index” 列表頁 – 顯示最新投票。
  • “detail” 投票頁 – 顯示一個投票的問題, 以及用戶可用于投票的表單。
  • “results” 結(jié)果頁 – 顯示一個投票的結(jié)果。
  • 投票處理 – 對用戶提交一個投票表單后的處理。

            現(xiàn)在修改 views.py 創(chuàng)建用于視圖的函數(shù)。

dizzy@dizzy-pc:~/Python/mysite$ vim polls/views.py
from django.shortcuts import render,get_object_or_404 # Create your views here.from django.http import HttpResponsefrom 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的自帶函數(shù),不做深究。后面再做研究!

            要想使試圖能被訪問,還要配置 urls.py 。mysite是整個網(wǎng)站的URLConf,但每個app可以有自己的URLConf,通過include的方式導(dǎo)入到根配置中即可。現(xiàn)在在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'^(?P<poll_id>/d+)/$',views.detail,name='detail'),  #ex:/polls/5/results/  url(r'^(?P<poll_id>/d+)/results/$',views.results,name='results'),  #ex:/polls/5/vote/  url(r'^(?P<poll_id>/d+)/vote/$',views.vote,name='vote'),)#url中,三個參數(shù)。正則的url,處理的函數(shù),以及名稱#正則表達式!!!!!

            然后在根 urls.py 文件中,include這個文件即可。

dizzy@dizzy-pc:~/Python/mysite$ vim mysite/urls.py
from django.conf.urls import patterns, include, url from django.contrib import adminadmin.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:兩種形式。因為是元組,所以開始有“ ‘', ”。

            然后開始創(chuàng)建模板文件。在polls下,創(chuàng)建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>{{ poll.question }}</h1><ul>{% for choice in poll.choice_set.all %}  <li>{{ choice.choice_text }}</li>{% endfor %}</ul> <!-- 視圖設(shè)置完畢,具體語法還要深入研究! --><!-- 現(xiàn)在重啟服務(wù), 便可看到相應(yīng)視圖 -->

        (4)投票功能完善

            上面只是簡單的實現(xiàn)了視圖功能,并沒有真正的實現(xiàn)投票功能。接下來就是完善功能。

#修改模板文件dizzy@dizzy-pc:~/Python/mysite$ vim polls/templates/polls/detail.html#需要加入form表單<h1>{{ 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>

            然后需要修改 views.py 中的 vote 處理函數(shù)。進行post數(shù)據(jù)的接收與處理。

# 文件 polls/views.py from django.shortcuts import get_object_or_404, renderfrom django.http import HttpResponseRedirect, HttpResponsefrom django.core.urlresolvers import reversefrom 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,)))

            在投票成功之后,讓用戶瀏覽器重定向到結(jié)果 results.html 頁。

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

            然后就需要創(chuàng)建模板 results.html 。

 

<!-- polls/templates/polls/results.html --> <h1>{{ 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?</a>

            至此,重啟服務(wù)就能看到單選按鈕,以及submit了。


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 鄂温| 西和县| 韶关市| 盐山县| 永嘉县| 沅陵县| 贵州省| 合江县| 丰县| 林甸县| 玉屏| 安塞县| 蛟河市| 商洛市| 尚志市| 巫山县| 嘉峪关市| 鲜城| 兖州市| 蕲春县| 沙坪坝区| 墨玉县| 五家渠市| 沽源县| 连山| 溧水县| 朝阳区| 中卫市| 嵩明县| 亚东县| 莱芜市| 大宁县| 台湾省| 铜山县| 绵阳市| 竹山县| 汝城县| 广州市| 含山县| 容城县| 玉门市|