Django 1.9.6 Official Document Part II (Chinese translation)

Source: Internet
Author: User
Tags install django

Note: Recently began to learn Python's Django framework, in order to urge learning, forcing themselves to translate the official documents, is a learning, but also a kind of accumulation! Because the experience is insufficient, the mistake certainly many, please everybody feel free! Original content, reproduced please indicate the source.

Django Official Document Part II: Getting Started

(starting from the second part, because the first part is the entire official document structure and guidance, I will translate it when I am free.) )

2.1 Django Overview

Django is born in a fast-paced newsroom environment and is designed to be a fast, simple, common web development tool.

The purpose of this document is to give you enough basic knowledge to understand how Django works, both as a tutorial and as a reference material. When you're ready to start a project, you can start with a tutorial or go directly to a more detailed document.

2.1.1 Model design

You can use Django without a database.

Data model syntax provides several ways to represent your model. Here's a short example:

mysite/news/models.py fromDjango.dbImportModelsclassReporter (models. Model): Full_name= Models. Charfield (max_length=70)    def __str__(self):#__unicode__ on Python 2        returnSelf.full_nameclassarticle (models. Model): Pub_date=models. Datefield () Headline= Models. Charfield (max_length=200) Content=models. TextField () Reporter= Models. ForeignKey (Reporter, on_delete=models. CASCADE)def __str__(self):#__unicode__ on Python 2        returnSelf.headline
2.1.2 Installation

You can create database tables automatically by running the Django command-line program:

$ Python manage.py Migrate

2.1.3 Open API

You can access the data using a large number of open Python APIs. These APIs are created quickly and do not require additional code generation. Here's an example:

Import Modules #从我们创建的 the news app

>>> from news.models import Reporter, article

# There's no reporters in the system at the moment

>>> Reporter. Objects. All ()

[]

#创建一个新的Reporter.

>>> R = Reporter (full_name=' John Smith ')

#将对象存入数据库. You have to explicitly call the Save method.

>>> R. Save ()

# now it has an ID.

>>> R. Id

#新的reporter存在于数据库

>>> Reporter. Objects. All ()

[<reporter:john Smith>]

#字段被当做Python对象的属性

>>> R. Full_name

' John Smith '

# Django provides a rich database query API.

>>> Reporter. Objects. Get (id=1)

< Reporter:john Smith>

>>> Reporter. Objects. Get (Full_name__startswith=' John ')

< Reporter:john Smith>

>>> Reporter. Objects. Get (Full_name__contains=' Mith ')

< Reporter:john Smith>

>>> Reporter. Objects. Get (id=2)

Traceback (most recent):

...

Doesnotexist:reporter matching query does not exist.

# Create a article

>>> from datetime Import Date

>>> A = article (pub_date=date. Today (), Headline=' Django is cool ',

... Content=' Yeah. ', reporter=r)

>>> a. Save ()

# article exists in the database

>>> Article. Objects. All ()

[<Article:django is cool>]

>>> R = a. Reporter

>>> R. Full_name

' John Smith '

>>> R. Article_set. All ()

[<Article:django is cool>]

>>> Article. Objects. Filter (Reporter__full_name__startswith=' John ')

[<Article:django is cool>]

#通过变更对象的属性修改对象, remember to call the Save method.

>>> R. Full_name = ' Billy Goat '

>>> R. Save ()

# Delete an object using the Delete () method

>>> R. Delete ()

2.1.4 Full-Featured management interface

Once your model is defined, Django will automatically create a professional, ready-made management interface. It is actually a Web page that allows authorized users to add, change, and delete objects.

mysite/news/models.pyfromimport  modelsclass  article (models. Model):    = models. Datefield ()    = models. Charfield (max_length=200)    = models. TextField ()    = models. ForeignKey (Reporter, On_delete=models. CASCADE)
mysite/news/admin.pyfromimport  adminfromImport  Modelsadmin.site.register (models. article)
2.1.5 to design your URLs

A clean, elegant URL scheme is an important part of high-quality web applications. Django encourages pretty URLs to design, and don't put those annoying. php or. asp into URLs.

Designing URLs for your app is actually creating a urlconf python module. It is the directory table for your app, which contains a simple mapping between the URL pattern and the Python callback function. Urlconfs helps decouple URLs and Python code.

Here is an example of a urlconf, which is used for the reporter/article example above:

mysite/news/urls.py fromDjango.conf.urlsImportURL from.ImportViewsurlpatterns=[url (r'^articles/([0-9]{4})/$', views.year_archive), url (r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive), url (r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', Views.article_detail),]

In the above code, the URLs are linked to the specific Python callback function (views) through a simple regular expression. The regular expression gets the value from the URL by parentheses. When a user requests a page, Django iterates through each of the matching patterns sequentially and stops at the first match. (Django returns a 404 page if there are no matches). This process is very fast because the regular expression is compiled when it is loaded.

Once successfully matched, Django will import and invoke the given view, a simple Python function. Each view passes a request object that contains the requested metadata and the values captured in the regular expression. For example, when a user requests the "/articles/2005/05/39323/" page, Django will call the function news.views.article_detail (Request, ' 2005 ', ' 05 ', ' 39323 ')

2.1.6 Edit View

Each view returns at least one HttpResponse object that contains the contents of the requested page or triggers an exception, such as Http404. The rest of the features are your own decision.

Typically, a view takes data through parameters and renders the loaded template with it. Here is an example of a year_archive view:

mysite/news/views.py fromDjango.shortcutsImportRender from. ModelsImportarticledefyear_archive (Request, year): A_list= Article.objects.filter (pub_date__year=Year ) Context= {' Year': Year,'article_list': A_list}returnRender (Request,'news/year_archive.html', context)

This example uses the Django template system, which has many powerful features and tries to keep it simple and easy to use.

2.1.7 Design your template

The above code loads the news/year_archive.html template.

Django has a template lookup path that allows you to reduce template redundancy. In Django settings, you can create a directory listing of templates, and Django will find the templates in the list in order.

Here is the code for the news/year_archive.html template:

mysite/news/templates/news/year_archive.html{% extends"base.html"%}{% Block Title%}articles for{{Year}} {% Endblock%}{% Block content%} for{{Year}}{% forArticleinchArticle_list%}    <p>{{Article.headline}}</p> <p>by {{article.reporter.full_name}}</p> <p>published {{article.pub_date|date:"F J, Y"}}</p>{% ENDFOR%}{% Endblock%}

The double curly braces enclose the variable. {{Article.headline}} means the value of the output article title bar. The dots are used not only to find properties, but also for dictionary key values, index lookups, and function calls. Note that the UNIX system-style pipe symbol "|" is used in {{article.pub_date|date: "F J, Y"}}. You can connect any number of pipes. You can write custom template pipelines, you can write custom template tags, and run custom back-end python code.

Finally, Django uses the concept of "template inheritance," just like {% extends "base.html"%}. It means that the template named "base" is loaded first. This template has pre-defined a large number of blocks, and the blocks are also nested within them. In short, this helps you to reduce the number of templates in large numbers, and each template only focuses on its unique parts.

The following is the code for "base.html".

mysite/templates/base.html{% load staticfiles%}"" Images/sitelogo.png"  %}" alt="Logo" />    { % block content%}{% endblock%}</body>

It simply defines the basic "look" of the site and provides a "portal" for the child template to populate. This makes it easy to redesign a site, and you only need to change the base template file.

Note that you can also use a different templating system, although the Django template system and its model layer are well-integrated, but not forcing you to use it. Similarly, you are not a non-Django database API. You can use the other database abstraction layer, you can read the XML file, whatever you want. Every part of Django, such as models, views, and templates, is loosely coupled.

2.2 Quick Install Wizard

Before using Django, we must install it first. The light has a complete installation wizard that contains all the possible conditions.

2.2.1 Installing Python

As a Python-based web framework, Django needs to pre-install Python. You can download and install the latest version of Python from Python's website or from the operating system's software manager. Also, to find out which version of Python supports Django, see the document "What Python version can I use with Django?". Python has a lightweight database called SQLite, so you don't have to install a database program at this point. If you're using Jython (the Python Java Platform implementation), you'll need some extra steps.

Enter Python in the shell to prove that Python has been successfully installed if the following information is displayed:

Python 3.4.x

[GCC 4.x] on Linux

Type "Help", "copyright", "credits" or "license" for more information.

>>>

2.2.2 Installing the Database

If you want to work under the "big" database engine, such as PostgreSQL, MySQL, or Oracle, check out the document "Database installation Information"

2.2.3 Removing old versions of Django

Before installing a new version of Django, you need to uninstall the old version first.

2.2.4 Installing Django

There are three options when you install Django:

• Installing Jango through the operating system's software management tools is the quickest method.

• Install the official release version. This is the best choice for most users.

• Install the latest development version. This applies to those who prefer to use the latest and most comprehensive features without worrying about the code risk. In the development version, you may encounter a new bug, please escalate it to help Django's development.

2.2.5 Verification

In a python shell environment, import the Django module as follows:

>>> Import Django

>>> print (Django.get_version ())

1.9

Cond.........

Django 1.9.6 Official Document Part II (Chinese translation)

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.