瞭解學習pyhton web的簡單demohtml
1. 安裝Django, 安裝pyhton 自行百度前端
2. 執行命令建立project django-admin.py startproject mysitepython
3. 執行命令建立app python manage.py startapp pollsmysql
目錄結構: polls/templates/polls 目錄 和 polls/admin.py 都是本身手動建立的。 web
4. 編輯setting.py 添加app polls 同時打開adminsql
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', )
5. 編輯setting.py 添加數據庫鏈接信息數據庫
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'polls', # Or path to database file if using sqlite3. 'USER': 'root', # Not used with sqlite3. 'PASSWORD': '123', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } }
6. 建立Modle模型 :django
# 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
7. 執行數據庫同步 (ORM)自動根據model定義建立表接口 (我這裏使用的mysql)session
首先建立數據庫 oracle
create database polls;
而後執行命令:
python manage.py syncdb
8. 檢查數據庫中表的建立:
use polls
show tables
9. 建立admin.py
# coding=utf-8 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)
10. 啓動應用
python manage.py runserver
登陸後臺:http://127.0.0.1:8000/admin 經過Django自動的後臺進行問題添加
11. 編寫視圖控制層
視圖起着承前啓後的做用,前是指前端頁面,後是指後臺數據庫。將數據庫表中的內容查詢出來顯示到頁面上。
編寫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,)))
12. 配置視圖展現層與邏輯控制層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)), ]
13. 建立視圖模板
模板就是前端頁面,用來將數據顯示到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>
14. 啓動web容器,訪問:http://127.0.0.1:8000/polls/