以一個投票程序的實例來講解Python的Django框架使用
(一)關于Django
Django是一個基于MVC構(gòu)造的框架。但是在Django中,控制器接受用戶輸入的部分由框架自行處理,所以 Django 里更關注的是模型(Model)、模板(Template)和視圖(Views),稱為 MTV模式。
Ubuntu下的安裝:一般都自帶Python的。網(wǎng)上教程比較多了....
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版本等信息。
(二)第一個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 Python dizzy@dizzy-pc:~$ cd Python #然后創(chuàng)建工程 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 #新創(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-us TIME_ZONE = 'Asia/Shanghai' #原:UTC #配置完之后,便可以創(chuàng)建數(shù)據(jù)表了 dizzy@dizzy-pc:~/Python/mysite$ python manage.py syncdb #創(chuàng)建是還要設置一個超級管理員,用于后臺登錄。 #設置完之后,開啟服務,便可進入后臺管理界面了:http://127.0.0.1:8000/admin/
(2)教你開始寫Django1.6的第1個app
#創(chuàng)建一個用于投票的app。 #進入mysite工程根目錄,創(chuàng)建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已經(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 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自動創(chuàng)建數(shù)據(jù)庫表了
要想在后臺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)
#這部分代碼,大體能看懂,具體的規(guī)則還要稍后的仔細研究。
##這部分代碼,由于拼寫失誤,導致多處出錯。細節(jié)決定成?。?!
這樣再重啟服務,就能在后臺管理polls應用了。
(3)視圖和控制器部分
前面已經(jīng)完成了model(M)的設置。剩下的只有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 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的自帶函數(shù),不做深究。后面再做研究!
要想使試圖能被訪問,還要配置 urls.py 。mysite是整個網(wǎng)站的URLConf,但每個app可以有自己的URLConf,通過include的方式導入到根配置中即可。現(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 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:兩種形式。因為是元組,所以開始有“ ‘', ”。
然后開始創(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>
<!-- 視圖設置完畢,具體語法還要深入研究! -->
<!-- 現(xiàn)在重啟服務, 便可看到相應視圖 -->
(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, 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,)))
在投票成功之后,讓用戶瀏覽器重定向到結(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>
至此,重啟服務就能看到單選按鈕,以及submit了。
- Django+mysql配置與簡單操作數(shù)據(jù)庫實例代碼
- Django admin實現(xiàn)圖書管理系統(tǒng)菜鳥級教程完整實例
- Django中實現(xiàn)一個高性能計數(shù)器(Counter)實例
- Python中DJANGO簡單測試實例
- 在python3環(huán)境下的Django中使用MySQL數(shù)據(jù)庫的實例
- pycharm+django創(chuàng)建一個搜索網(wǎng)頁實例代碼
- Django實現(xiàn)快速分頁的方法實例
- python django 實現(xiàn)驗證碼的功能實例代碼
- 用ReactJS和Python的Flask框架編寫留言板的代碼示例
- Django開發(fā)的簡易留言板案例詳解
相關文章
深入理解Pytorch微調(diào)torchvision模型
PyTorch是一個基于Torch的Python開源機器學習庫,用于自然語言處理等應用程序。它主要由Facebookd的人工智能小組開發(fā),不僅能夠 實現(xiàn)強大的GPU加速,同時還支持動態(tài)神經(jīng)網(wǎng)絡,這一點是現(xiàn)在很多主流框架如TensorFlow都不支持的2021-11-11
pycharm中如何自定義設置通過“ctrl+滾輪”進行放大和縮小實現(xiàn)方法
這篇文章主要介紹了pycharm中如何自定義設置通過“ctrl+滾輪”進行放大和縮小實現(xiàn)方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09
Python實現(xiàn)輸出某區(qū)間范圍內(nèi)全部素數(shù)的方法
這篇文章主要介紹了Python實現(xiàn)輸出某區(qū)間范圍內(nèi)全部素數(shù)的方法,涉及Python數(shù)值運算、排序、判斷等相關操作技巧,需要的朋友可以參考下2018-05-05

