Use an example of a voting program to explain how to use the Python Django framework

Source: Internet
Author: User
This article mainly introduces how to use the Python Django framework using an example of a voting program. Django is the most popular MVC Framework in the Python world. For more information, see (1) about Django

Django is a framework constructed based on MVC. However, in Django, the Framework processes the part that the controller accepts user input. Therefore, Django focuses more on models, templates, and Views ), it is called the MTV mode.

Install Python in Ubuntu. More online tutorials ....

Digoal @ digoal-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) # You can view django VERSION and other information.

(2) The first Django app

# Environment: Python2.7, Django1.6, Ubuntu12.04
After Python and Django are installed successfully, you can create a Django project.

(1) teach you to start writing 1st Django1.6 apps

# Create a folder digoal @ digoal-pc :~ $ Mkdir pythondi.pdf @ dimo-- pc :~ $ Cd Python # create a project digoal @ digoal-pc :~ /Python $ django-admin.py startproject mysitedi.pdf @ dimo-- pc :~ /Python $ cd mysite # Then this project can start the service digoal @ digoal-pc :~ /Python/mysite $ python manage. py runserverValidating models... 0 errors foundJuly 23,201 4-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. # in this way, open the browser to access: You can see: It Worked! Close the service: ctrl + c # the newly created project contains: manage. py file, mysite folder # The mysite folder contains :__ init __. py, settings. py, urls. py, wsgi. four py files #__ init __. py is an empty file, # setting. py is the configuration file of the project. You need to modify two places, here use the default SQLite3 Database Export age_code = 'zh-cn' # Original: en-usTIME_ZONE = 'Asia/Shanghai' # Original: UTC # After configuration, you can create the data table digoal @ digoal-pc :~ /Python/mysite $ python manage. py syncdb # create a super administrator for background logon. # After the configuration is complete, enable the Service to go to the background management interface: http: // 127.0.0.1: 8000/admin/

(2) teach you to start writing 1st Django1.6 apps


# Create an app for voting. # Go To The mysite project root directory and create appdigoal @ digoal-pc :~ /Python/mysite $ python manage. py startapp pollsdigoal @ digoal-pc :~ /Python/mysite $ ls pollsadmin. py _ init _. py models. py urls. py views. py. Django has been generated, and the template file is usually required by the app.

Create two models. 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 hhed ') class Choice (models. model): poll = models. foreignKey (Poll) choice_text = models. charField (max_length = 200) votes = models. integerField (default = 0) # This is the basic process for creating a model. Further research is required!

Modify the project configuration file setting. py and add the created app: polls under the INSTALLED_APP tuples.

Digoal @ digoal-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',) # You can use python manage. py SQL polls view the app's table creation SQL # Use python manage. py syncdb to create the database table digoal @ digoal-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; # This allows Django to automatically create database tables by setting the model. Manage polls in admin. You 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 class PollAdmin (admin. modelAdmin): fieldsets = [(None, {'fields': ['Question ']}), ('date information', {'fields ': ['pub _ date'], 'class': ['collapse']}),] inlines = [ChoiceInLine] admin. site. register (Poll, PollAdmin) # This part of the code is easy to understand. The specific rules will be carefully studied later. # This part of code may cause multiple mistakes due to spelling mistakes. Details determine success or failure !!


Then restart the Service to manage the polls application in the background.

(3) view and Controller

The model (M) settings have been completed before. Only view (V) and urls (C) are left. The view section of Django is completed by views. py and templates.

In polls, we will create four views:

  • "Index" list page-displays the latest vote.
  • "Detail" Vote page-displays a vote question and a form that the user can use for voting.
  • "Results" result page-displays the result of a vote.
  • Voting processing-processing after a user submits a voting form.

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 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, 'lls/index.html', context) def detail (request, poll_id): poll = get_object_or_404 (Poll, pk = poll_id) ret Urn 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) # The built-in functions of Django are involved. Study later!

To make the attempt accessible, configure urls. py. Mysite is the URLConf of the entire website, but each app can have its own URLConf, which can be imported to the root configuration through the include method. Now create urls. py under polls

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
 
  
\ D +)/$ ', views. detail, name = 'detail'), # ex:/polls/5/results/url (R' ^ (? P
  
   
\ D +)/results/$ ', views. results, name = 'result'), # ex:/polls/5/vote/url (R' ^ (? P
   
    
\ D +)/vote/$ ', views. vote, name = 'Vote'),) # Three parameters in url. Regular url, processed function, and name # regular expression !!!!!
   
  
 

Then, in the root urls. py file, include the 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 = 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),) # There are two forms: Example. Because it is a tuples, "'', "is started.

Then, create a template file. Under polls, create the templates folder. The following two files are available: index.html and detail.html.

 {% If latest_poll_list %}
 
 
    {% For poll in latest_poll_list %}
  • {Poll. question }}
  • {% Endfor %}
{% Else %}

No polls are available.

{% Endif %} {Poll. question }}
    {% For choice in poll. choice_set.all %}
  • {Choice. choice_text }}
  • {% Endfor %}

(4) complete voting Functions

The above simply implements the view function, and does not actually implement the voting function. The next step is to improve functions.

# Modify the template file digoal @ digoal-pc :~ /Python/mysite $ vim polls/templates/polls/detail.html # Add form {poll. question }}{% if error_message %}

{Error_message }}

{% Endif %}

Modify the vote Processing Function in views. py. Receive and process post data.

# File 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 ']) handle T (KeyError, choice. doesNotExist): # Redisplay the poll voting form. return render (request, 'lls/detail.html ', {'Poll': p, 'error _ message': "You did' 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, redirect the user's browser to the results.html page of the result.

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?

Now, restart the service to see the single-choice button and 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.