Use an example of a voting program to illustrate Python's Django framework usage

Source: Internet
Author: User
Tags browser redirect
(i) About Django

Django is a framework based on MVC constructs. But in Django, the part of the controller that accepts user input is handled by the framework itself, so Django is more concerned with models, templates, and views, called MTV mode.

Installation under Ubuntu: usually comes with python. Online tutorials are much more ....

dizzy@dizzy-pc:~$ Pythonpython 2.7.3 (default, APR, 22:44:07) [GCC 4.6.3] on Linux2type "help", "copyright", "cred Its "or" license "for more information.>>> import django>>> Help (Django) VERSION = (1, 6, 4, ' final ', 0) # You can view information such as the Django version.

(ii) the first Django app

#环境: python2.7,django1.6,ubuntu12.04
Once the Python and Django installations are successful, you can create a Django project

(1) Teach you to start writing Django1.6 's 1th app

#先创建一个文件夹dizzy @dizzy-pc:~$ mkdir pythondizzy@dizzy-pc:~$ cd python# and then create the project dizzy@dizzy-pc:~/python$ django-admin.py Startproject mysitedizzy@dizzy-pc:~/python$ CD mysite# then this project will start serving the dizzy@dizzy-pc:~/python/mysite$ Python manage.py runservervalidating Models ...  0 Errors foundjuly, 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. #这样, open browser access: You can see: It worked! Close Service: Ctrl + C #新创建的项目里面会有: manage.py file, MySite folder # in MySite folder will have: __init__.py,settings.py,urls.py,wsgi.py four files #__init __.py is an empty file, #setting. py is the configuration file for the project. There are two places to modify, using the default SQLite3 database Language_code = ' ZH-CN ' #原: en-ustime_zone = ' Asia/shanghai ' #原: UTC #配置完之后, You can create a data table dizzy@dizzy-pc:~/python/mysite$ Python manage.py syncdb# Create is also to set up a super administrator for the background login. #设置完之后, open the service, you can enter the background management interface: http://127.0.0.1:8000/admin/

(2) teach you to start writing Django1.6 's 1th app


#创建一个用于投票的app. #进入mysite工程根目录, create 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 has generated the template files that the app typically needs.

Create two models below. Poll and Choice

dizzy@dizzy-pc:~/python/mysite$ Vim polls/models.py

Modify the file as follows:

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过程就是这样, the details of further study!

Then modify the project's configuration file setting.py, add the app:polls you just created under the Installed_app tuple

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 view the app's build table sql# use Python manage.py syncdb to create a database table di zzy@dizzy-pc:~/python/mysite$./manage.py SQL Pollsbegin; CREATE TABLE "Polls_poll" ("id" integer NOT NULL PRIMARY KEY, "question" varchar ($) NOT NULL, "Pub_date" datetime NO T NULL); CREATE TABLE "Polls_choice" ("id" integer NOT NULL PRIMARY KEY, "poll_id" integer NOT null REFERENCES "Polls_poll" ("ID ")," choice_text "varchar (no null)," votes "integer NOT NULL); COMMIT; #这样就可以通过设置model让Django自动创建数据库表了 want to manage polls in background admin. You will also need to modify the admin.py file under the app. 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 clPolladmin (admin. Modeladmin): FieldSets = [(None, {' Fields ': [' question ']}), (' Date information ', {' Fields ': [' pub_date '], ' C Lasses ': [' Collapse ']},] inlines = [Choiceinline] Admin.site.register (poll,polladmin) #这部分代码, generally understand, the specific rules to be carefully studied later. # #这部分代码, there are many errors due to spelling mistakes. Details determine success or failure!!


Then restart the service, you can manage the polls application in the background.

(3) View and Controller section

The setup of model (M) has already been completed earlier. The rest is only view (V) and URLs (C). The Django View section is done by views.py and templates.

In polls, we will create 4 views:

    • Index List Page – Displays the latest poll.
    • "Detail" Poll page – Displays a poll question and a form that the user can use to vote.
    • "Results" Results page – Displays the results of a poll.
    • Voting processing – The process of submitting a poll form to a user.

Now modify views.py to create a function for the view.

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 PO Lls.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 ':p Oll}) 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的自带函数, do not delve into it. Go back and do the research!

To make an attempt to be accessed, you also configure urls.py. MySite is the urlconf of the entire site, but each app can have its own urlconf, which is imported into the root configuration via the Include method. Now create a new urls.py under polls

From Django.conf.urls import Patterns,url to polls import views Urlpatterns = Patterns (",  #ex:/polls/  url (r ' ^ $ ', views.index,name= ' index '),  #ex:/polls/5/  url (r ' ^ (? P
 
  
   
  \d+)/$ ', views.detail,name= ' detail '),  #ex:/polls/5/results/  url (r ' ^ (? P
  
   
    
   \d+)/results/$ ', views.results,name= ' results '),  #ex:/polls/5/vote/  url (r ' ^ (? P
   
    
     
    \d+)/vote/$ ', views.vote,name= ' vote '), #url中, three parameters. Regular URLs, processed functions, and name # REGULAR Expressions!!!!!
   
    
  
   
 
  

Then in the root urls.py file, include this file.

dizzy@dizzy-pc:~/python/mysite$ Vim mysite/urls.py

From Django.conf.urls import patterns, include, url from django.contrib import adminadmin.autodiscover () Urlpatterns = Pat Terns (',  # 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: two forms. Because it is a tuple, it starts with "',".

Then start creating the template file. Under polls, create the Templates folder. Below are index.html, detail.html two files.

 
  {% if latest_poll_list%}  
 
  
  
    {% for poll in latest_poll_list%}
  • {{Poll.question}}
  • {% endfor%}
{% Else%}

No polls is available.

{% ENDIF%}

{{Poll.question}}

    {% for choice in poll.choice_set.all%}
  • {{Choice.choice_text}}
  • {% ENDFOR%}

(4) Perfect voting function

The above is simply the implementation of the view function, and does not really implement the voting function. The next step is to refine the function.

#修改模板文件dizzy @dizzy-pc:~/python/mysite$ vim polls/templates/polls/detail.html# need to join form form

{{Poll.question}}

{% if error_message%}

{{Error_message}}

Then you need to modify the vote processing function in views.py. To receive and process post data.

# files polls/views.py from django.shortcuts import get_object_or_404, renderfrom django.http import Httpresponseredirect, H Ttpresponsefrom 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,)))

After the vote is successful, let the user's browser redirect to the results results.html page.

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

Then you need to create the template results.html.


 
  

{{Poll.question}}

    {% for choice in poll.choice_set.all%}
  • {{Choice.choice_text}}--{{choice.votes}} vote{{Choice.votes|pluralize}}
  • {% endfor%}
Vote again?

At this point, the restart Service will be able to see the radio button, as well as the submit.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.