Introduction to using Python and Django to build a web App Django is a web framework developed by Python. It's easy to build Web apps with Django. The latest version of Django is 1.4 when writing this article, but this article does not focus on the features of the new version, just a simple application. Installing Django This article installs the CentOS 6.2 example: Installing python# Yum Install python This article uses the CentOS 6.2 Desktop, which is installed by default with Python. Check Python version # python--versionpython 2.6.6django-1.4 support python above 2.5 (Python3 is not supported). See Django's official blog for details. Install SETUPTOOLS,PIP based on Python (using PIP to install the software is easy, Pip relies on Setuptools), the installation setuptools is simple, to its pipy download and install (note the Python version corresponds). # Curl-o http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c11-py2.6.egg# SH setuptools-0.6c11-py2.6.egg# Curl-o https://raw.github.com/pypa/pip/master/contrib/get-pip.py# python get-pip.py This article focuses on Django and does not take into account the installation of virtual environments such as Virtualenv,buildout. Install django# pip install Django View Django version $ django-admin.py--version1.4 Create a Django project and web App use Django to build a web app quickly. $ mkdir ~/dev$ CD ~/dev Create the project, using the django-admin.py startproject command. ~/dev$ django-admin.py startproject djdemodjango-1.4 The directory structure created by the previous version has some adjustments, the example of this article is as follows:. '--djdemo |--djdemo | |--__init__.py | |--settings.py | |--urls.py | The '--wsgi.py '--manage.py create an app, using the manage.py startapp command, to create an order example for this article. $ cd djdemo~/dev/djdemo$ python manage.py startapp Ordersdjango automatically creates the basic files for this app, the directory is as follows:. '--djdemo |--djdemo | |--__init__.py | |--settings.py | |--urls.py | '--wsgi.py+ |--orders+ | |--__init__.py+ | |--models.py+ | |--tests.py+ | The '--views.py '--manage.py creates a new admin.py in the Orders folder for use with the Django management tool. The final directory is as follows:. '--djdemo |--djdemo | |--__init__.py | |--settings.py | |--urls.py | '--wsgi.py |--orders | |--__init__.py+ | |--admin.py | |--models.py | |--tests.py | '--views.py '--manage.py create a Django model and then modify the models.py to manage this due model. Note: If you use non-ASCII code, add the #-*-Coding:utf-8-*-to the file header to add the Order model: #-*-coding:utf-8-*-from django.db import models# Crea Te your models here.from django.utils.translation import Ugettext_lazy as _class Order (models. Model): Order_no = models. Charfield (max_length=255) Description = models. Charfield (Max_length=255) created_on = models. Datetimefield (Help_text=_ (' creation Date '), Auto_now_add = True) updated_on = models. Datetimefield (Help_text=_ (' Last update Date '), Auto_now = True) def __unicode__ (self): return self.order_no This is a Models's example, designed to attribute, internationalize, autofill time, and more, refer to models for more information on the Django website models related documents. The following is the content of admin.py, which allows Django to manage this model. Usually only need to add the following example: #-*-coding:utf-8-*-from django.contrib import adminfrom. Models Import Orderadmin.site.register ( Order) But Django can customize the management interface. The following changes: #-*-coding:utf-8-*-from django.contrib import adminfrom django.utils.translation import Ugettext_lazy as _from. m Odels Import Orderclass orderadmin (admin. Modeladmin): "" "Admin form Order model" "List_display = (' order_no ', ' description ', ' created_on ') search_fields = (' order_no ', ' description ') FieldSets = ((_ (' Content '), {' Fields ': (' order_no ', ' description ') }), (_ (' Advanced options '), {' Classes ': (' collapse ',), ' Fields ': (' creatEd_on ', ' updated_on ')}), Actions_on_top = True Actions_on_bottom = True Readonly_fields = ("Created_ On "," updated_on ") Admin.site.register (Order, orderadmin) This is an example of admin, related to list display, Search, config interface, etc., about admin, more please refer to the Django website documentation Admin related documents. Configure the primary configuration settings.py and urls.py. At settings.py start adding the following, the main setting path: #-*-coding:utf-8-*-# Django settings for Djdemo project.import osimport sysroot_path = os. Path.dirname (Os.path.abspath (__file__)) if Root_path not in Sys.path:sys.path.append (Root_path) modifies the database configuration, this article uses Sqlite3, This is a Django-driven, other reference to the Django website's database related document databases = {' Default ': ' ENGINE ': ' Django.db.backends.sqlite3 ' , # Add ' postgresql_psycopg2 ', ' MySQL ', ' sqlite3 ' or ' Oracle '. ' NAME ': Os.path.abspath (Os.path.join (Root_path, '. ', ' sqlite.db ')), # Or path to database file if using Sqlite3. ' USER ': ', # not used with Sqlite3. ' PASSWORD ': ', # 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. Next, modify the Installed_apps section: Add the Orders app to the Installed_apps settings and remove the # comment from the admin module. Installed_apps = (' Django.contrib.auth ', ' django.contrib.contenttypes ', ' django.contrib.sessions ', ' django.co Ntrib.sites ', ' django.contrib.messages ', ' Django.contrib.staticfiles ', # uncomment the next line to enable the ad Min: ' Django.contrib.admin ', # uncomment the next line to enable admin documentation: # ' Django.contrib.admindoc S ',) Installed_apps + = (' orders ',) configuration urls.py. To make the administration tool available through the/admin URL, simply cancel the contents of the corresponding row provided in the project's urls.py file. #-*-Coding:utf-8-*-from django.conf.urls Import patterns, include, url# uncomment the next lines to enable the ADM In:from django.contrib Import adminadmin.autodiscover () Urlpatterns = Patterns (", # Examples: # URL (r ' ^$ ', ' djdemo.v Iews.home ', name= ' home '), # URL (r ' ^djdemo/', Include (' Djdemo.foo.urls '), # uncomment the Admin/doc line below to enable admin documentation: # URL (r ' ^admin/doc /', include (' Django.contrib.admindocs.urls '), # Uncomment the next line to enable the Admin:url (R ' ^admin/', includ E (Admin.site.urls)), at this point, the basic configuration of the program is complete, starting with the database initialization and the Django management interface. The SQL statement is displayed first to see if the table structure is correct (you must indicate the application name, this article is orders). Use the manage.py sqlall command. ~/dev/djdemo$ python manage.py sqlall orders get the following results begin; CREATE TABLE "Orders_order" ("id" integer NOT NULL PRIMARY KEY, "order_no" varchar (255) is not NULL, "description" varchar (255) is not NULL, "CREATED_ON" datetime is NOT NULL, "UPDATED_ON" datetime is NOT NULL); The next step is to start the database initialization, use the manage.py syncdb command, and ask if you want to add Superusers, as follows: ~/dev/djdemo$ python manage.py syncdbcreating Tables ... Creating table auth_permissioncreating table auth_group_permissionscreating table auth_groupcreating table Auth_user_ user_permissionscreating table auth_user_groupscreating table auth_usercreating table Django_content_typecreaTing table django_sessioncreating table django_sitecreating table django_admin_logcreating table orders_order you just Installed Django's auth system, which means you don ' t has any superusers defined. Would to create one now? (yes/no): Yesusername (leave blank to use ' * * * *): Admine-mail address: [Email protected]password:password (again): Superuser created successfully. Installing Custom SQL ... Installing indexes ... Installed 0 object (s) from 0 fixture (s) at this point the database initialization is complete. Test start Django, apply the test, and use the manage.py runserver command to turn on the service. ~/dev/djdemo$ python manage.py runserver can now be accessed http://localhost:8000/admin view.
Build Web apps with Python and Django