https://docs.djangoproject.com/en/1.8/intro/tutorial01/
參考官網文檔,創建投票系統。
================
Windows 7/10
Python 2.7.10
Django 1.8.2
================
1、創建項目(mysite)與應用(polls)
D:\pydj>django-admin.py startproject mysite
D:\pydj>cd mysite
D:\pydj\mysite>python manage.py startapp polls
添加到setting.py
# Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', )
最終哪個目錄結構:
2、創建模型(即數據庫)
一般web開發先設計數據庫,數據庫設計好了,項目就完了大半了,可見數據庫的重要性。打開polls/models.py編寫如下:
# coding=utf-8 from django.db import models # Create your models here. # 問題 class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): return self.question_text # 選擇 class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __unicode__(self): return self.choice_text
執行數據庫表生成與同步。
D:\pydj\mysite>python manage.py makemigrations polls Migrations for 'polls': 0001_initial.py: - Create model Question - Create model Choice - Add field question to choice D:\pydj\mysite>python manage.py syncdb …… You have installed Django's auth system, and don't have any superusers defined. Would you like to create one now? (yes/no): yes Username (leave blank to use 'fnngj'): 用戶名(默認當前系統用戶名) Email address: fnngj@126.com 郵箱地址 Password: 密碼 Password (again): 重復密碼 Superuser created successfully.
3、admin管理
django提供了強大的后台管理,對於web應用來說,后台必不可少,例如,當前投票系統,如何添加問題與問題選項?直接操作數據庫添加,顯然麻煩,不方便,也不安全。所以,管理后台就可以完成這樣的工作。
打開polls/admin.py文件,編寫如下內容:
from django.contrib import admin from .models import Question, Choice # Register your models here. class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] list_display = ('question_text', 'pub_date') admin.site.register(Choice) admin.site.register(Question, QuestionAdmin)
當前腳本的作用就是將模型(數據庫表)交由admin后台管理。
運行web容器:
D:\pydj\mysite>python manage.py runserver Performing system checks... System check identified no issues (0 silenced). October 05, 2015 - 13:08:12 Django version 1.8.2, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK.
登錄后台:http://127.0.0.1:8000/admin
登錄密碼就是在執行數據庫同步時設置的用戶名和密碼。
點擊“add”添加問題。
4、編寫視圖
視圖起着承前啟后的作用,前是指前端頁面,后是指后台數據庫。將數據庫表中的內容查詢出來顯示到頁面上。
編寫polls/views.py文件:
# coding=utf-8 from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from .models import Question, Choice # Create your views here. # 首頁展示所有問題 def index(request): # latest_question_list2 = Question.objects.order_by('-pub_data')[:2] latest_question_list = Question.objects.all() context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) # 查看所有問題 def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) # 查看投票結果 def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question}) # 選擇投票 def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': 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,)))
5、配置url
url是一個請求配置文件,頁面中的請求轉交給由哪個函數處理,由該文件決定。
首先配置polls/urls.py(該文件需要創建)
from django.conf.urls import url from . import views urlpatterns = [ # ex : /polls/ url(r'^$', views.index, name='index'), # ex : /polls/5/ url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), # ex : /polls/5/results/ url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), # ex : /polls/5/vote url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ]
接着,編輯mysite/urls.py文件。
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls', namespace="polls")), url(r'^admin/', include(admin.site.urls)), ]
6、創建模板
模板就是前端頁面,用來將數據顯示到web頁面上。
首先創建polls/templates/polls/目錄,分別在該目錄下創建index.html、detail.html和results.html文件。
index.html
{% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %}
detail.html
<h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.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>
results.html
<h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'polls:detail' question.id %}">Vote again?</a>
7、功能展示
啟動web容器,訪問:http://127.0.0.1:8000/polls/
==========
django相關文章:
http://www.cnblogs.com/fnng/category/581256.html