SoFunction
Updated on 2024-11-15

An example of a voting program to explain the use of Python's Django framework

(i) About Django

Django is a framework based on MVC constructs. However, in Django, the controller accepts user input from the part of the framework itself , so Django is more concerned about the model (Model), templates (Template) and views (Views), known as the MTV pattern.

Installation under Ubuntu: usually comes with Python. There are more tutorials online ....

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)
# You can view information such as django version.

(ii) The first Django app

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

(1) Teaching you to start writing the 1st app for Django 1.6

# Create a folder first
dizzy@dizzy-pc:~$ mkdir Python
dizzy@dizzy-pc:~$ cd Python
# Then create the project
dizzy@dizzy-pc:~/Python$  startproject mysite
dizzy@dizzy-pc:~/Python$ cd mysite
# Then the project can start the service
dizzy@dizzy-pc:~/Python/mysite$ python  runserver
Validating models...
 
0 errors found
July 23, 2014 - 14:17:29
Django version 1.6.4, using settings ''
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
#This way, open your browser and visit: You will see: It Worked!
 
# Inside the newly created project will be: files, mysite folder
# Inside the mysite folder there will be: __init__.py,,, four files
 
#__init__.py is an empty file.
# is the configuration file for the project. Two changes are needed, here the default SQLite3 database is used
LANGUAGE_CODE = 'zh-cn' # Original: en-us
TIME_ZONE = 'Asia/Shanghai' # Original: UTC
 
# Once configured, you can create the data table
dizzy@dizzy-pc:~/Python/mysite$ python  syncdb
#Create is also to set up a super administrator for backend login.
#After setting up, turn on the service and you'll be able to access the backend management interface: http://127.0.0.1:8000/admin/

(2) Teaching you to start writing the 1st app for Django 1.6


#Create an app for voting.
# Go to the mysite project root directory and create the app
dizzy@dizzy-pc:~/Python/mysite$ python  startapp polls
dizzy@dizzy-pc:~/Python/mysite$ ls polls
  __init__.py     
 
# This way. Django has generated, the template files that the app would normally require.

Create two models, Poll and Choice.

dizzy@dizzy-pc:~/Python/mysite$ vim polls/

Modify the file as follows:

from  import models
 
# Create your models here.
 
from  import models
 
class Poll():
  question = (max_length=200)
  pub_date = ('date published')
 
class Choice():
  poll = (Poll)
  choice_text = (max_length=200)
  votes = (default=0)
# The basic process of creating a model is this, the details have to be studied in depth!

Then modify the project's configuration file and add the app you just created under the INSTALLED_APP tuple: polls

dizzy@dizzy-pc:~/Python/mysite$ vim mysite/
 
INSTALLED_APPS = (
  '',
  '',
  '',
  '',
  '',
  '',
  'polls',
)
 
#You can use python sql polls to view the app's table building SQL
# Create database tables using python syncdb
dizzy@dizzy-pc:~/Python/mysite$ ./ 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;
 
# This allows Django to automatically create database tables by setting up a model
    To get in the backgroundadminmiddle managementpolls。Also needs to be modifiedapplower file。

from  import admin
 
# Register your models here.
 
from  import admin
from  import Choice,Poll
 
class ChoiceInLine():
  model = Choice
  extra = 3
 
class PollAdmin():
  fieldsets = [
    (None,         {'fields':['question']}),
    ('Date information',  {'fields':['pub_date'],'classes':['collapse']}),
  ]
  inlines = [ChoiceInLine]
 
(Poll,PollAdmin)
 
# This part of the code, generally understandable, the specific rules have to be a little later to scrutinize.
## This part of the code, due to a spelling error, resulted in multiple errors. The details make the difference!


This will restart the service again and you will be able to manage the polls application in the background.

(3) View and controller section

The model (M) has already been set up. All that's left is view (V) and urls (C), the view part of Django, which is completed by and templates.

In polls, we will create 4 views:

  • "index" list page - shows the latest votes.
  • "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.
  • Poll Processing - Processing of a poll form after it has been submitted by a user.

Now modify Create functions for views.

dizzy@dizzy-pc:~/Python/mysite$ vim polls/

from  import render,get_object_or_404
 
# Create your views here.
from  import HttpResponse
from  import Poll
 
def index(request):
  latest_poll_list = ().order_by('-pub_date')[:5]
  context = {'latest_poll_list':latest_poll_list}
  return render(request,'polls/',context)
 
def detail(request,poll_id):
  poll = get_object_or_404(Poll,pk=poll_id)
  return render(request,'polls/',{'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)
 
# Involves Django's own functions, without going deeper. Do research later!

To make the attempt accessible, there is also configuration .mysite is the URLConf for the whole site, but each app can have its own URLConf, which can be imported into the root configuration by means of an include. Now under polls create a new

from  import patterns,url
 
from polls import views
 
urlpatterns = patterns('',
  #ex:/polls/
  url(r'^$',,name='index'),
  #ex:/polls/5/
  url(r'^(?P<poll_id>\d+)/$',,name='detail'),
  #ex:/polls/5/results/
  url(r'^(?P<poll_id>\d+)/results/$',,name='results'),
  #ex:/polls/5/vote/
  url(r'^(?P<poll_id>\d+)/vote/$',,name='vote'),
)
In #url, three parameters. The regular url, the function to process it, and the name of the
#RegularExpressions !!!!!

Then in the root file, include this file.

dizzy@dizzy-pc:~/Python/mysite$ vim mysite/

from  import patterns, include, url
 
from  import admin
()
 
urlpatterns = patterns('',
  # Examples:
  # url(r'^$', '', name='home'),
  # url(r'^blog/', include('')),
 
  url(r'^polls/', include('',namespace="polls")),
  url(r'^admin/', include()),
)
# There are Example: two forms. Because it's a tuple, it starts with " ' ', ".

Then start creating template files. Under polls, create the templates folder. Underneath there are, two files.

<!--  -->
{% if latest_poll_list %}
  <ul>
  {% for poll in latest_poll_list %}
    <li><a href="{% url 'polls:detail' poll_id= %}">{{  }}</a></li>
  {% endfor %}
  </ul>
{% else %}
  <p>No polls are available.</p>
{% endif %}
 
<!---->
<h1>{{  }}</h1>
<ul>
{% for choice in poll.choice_set.all %}
  <li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
 
<!-- View setup complete,We'll have to go deeper into the grammar.! -->
<!-- Now restart the service., You will see the corresponding view -->

(4) Improvement of voting function

The above is just a simple implementation of the view functionality, and does not really implement the voting functionality. The next step is to improve the functionality.

# Modify template files
dizzy@dizzy-pc:~/Python/mysite$ vim polls/templates/polls/
# need to add the form

<h1>{{  }}</h1>
 
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
 
<form action="{% url 'polls:vote'  %}" method="post">
{% csrf_token %}
{% for choice in poll.choice_set.all %}
  <input type="radio" name="choice"  value="{{  }}" />
  <label for="choice{{  }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>

Then you need to modify the vote handler in to receive and process the post data.

# Documentation polls/
 
from  import get_object_or_404, render
from  import HttpResponseRedirect, HttpResponse
from  import reverse
from  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=['choice'])
  except (KeyError, ):
    # Redisplay the poll voting form.
    return render(request, 'polls/', {
      '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=(,)))

After a successful vote, redirect the user's browser to the results page.

def results(request, poll_id):
  poll = get_object_or_404(Poll, pk=poll_id)
  return render(request, 'polls/', {'poll': poll})

Then it's time to create the template .


<!-- polls/templates/polls/ -->
 
<h1>{{  }}</h1>
 
<ul>
{% for choice in poll.choice_set.all %}
  <li>{{ choice.choice_text }} -- {{  }} vote{{ |pluralize }}</li>
{% endfor %}
</ul>
 
<a href="{% url 'polls:detail'  %}">Vote again?</a>

At this point, restart the service to see the radio buttons, and SUBMIT.