Django + MySQL Quick build simple web voting system

Source: Internet
Author: User
Tags install django

Learn about the simple demo of Learning Pyhton Web

1. Install Django, install Pyhton self-Baidu

2. Execute the command to create the project django-admin.py startproject MySite

3. Execute the command to create the app Python manage.py startapp polls

Directory structure: The Polls/templates/polls directory and the polls/admin.py are created manually by themselves.

4. Edit setting.py Add app polls also open admin

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 ad Min Documentation:    # ' Django.contrib.admindocs ',)

5. Edit setting.py Add database connection information

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. Create the Modle model:

# coding=utf-8from 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_textclass 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. Perform database synchronization (ORM) to automatically create a table interface based on the model definition (MySQL I use here)

Create a database First

Create database polls;

Then execute the command:

Python manage.py syncdb

8. Check the creation of tables in the database:

Use polls

Show tables

9. Create admin.py

# coding=utf-8from Django.contrib import adminfrom. Models import Question, choice# Register your models Here.class Choice Inline (admin. Tabularinline):    model = Choice    extra = 3class 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. Launch the App

Python manage.py runserver

Login background: Http://127.0.0.1:8000/admin through Django Auto-background to add problems

11. Writing the View Control layer

The view plays an important role, before it refers to the front page, and then the background database. Queries the contents of a database table to appear on the page.

To write a polls/views.py file:

# Coding=utf-8from Django.shortcuts Import Render, Get_object_or_404from django.http import Httpresponseredirect, Httpresponsefrom django.core.urlresolvers import reversefrom. Models import Question, choice# Create your views here.# home exhibition  Show All Issues 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) # View all Issues def detail (request, question_id): question = get_object_or_404 (question, pk=question_id) ret Urn render (Request, ' polls/detail.html ', {' question ': question}) # View the results of the poll DEF results (request, question_id): question = g et_object_or_404 (Question, pk=question_id) return render (Request, ' polls/results.html ', {' Question ': Question}) # Select Vote 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 C Hoice. ",}) Else:selected_choice.votes + = 1 selected_choice.save () # always return an Http Responseredirect 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. Configure the view presentation layer and the logical control layer URL mapping

A URL is a request configuration file that is determined by which function is processed by the request in the page.

First configure polls/urls.py (the file needs to be created)

From Django.conf.urls import Urlfrom. Import Viewsurlpatterns = [    # 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 '),]

  

Next, edit the mysite/urls.py file.

From Django.conf.urls import include, urlfrom django.contrib import adminurlpatterns = [    url (R ' ^polls/', include (' Polls.urls ', namespace= "polls"),    url (r ' ^admin/', include (Admin.site.urls)),]

  

13. Create a View template

A template is a front-end page used to display data on a Web page.

First create the polls/templates/polls/directory, where you create the index.html, detail.html, and results.html files, respectively.

Index.html

{% if latest_question_list%}    <ul>    {% for question in latest_question_list%}        <li><a href= "{% URL polls:detail question.id%}" & Gt {{Question.question_text}}</a></li>    {% endfor%}    </ul>{% Else%}    <p>no polls is available.</p>{% endif%}

  

Detail.html

  

Results.html

  

14. Launch the Web container, Access: http://127.0.0.1:8000/polls/

Django + MySQL Quick build simple web voting system

Related Article

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.