Python-django-Preliminary Understanding __python

Source: Internet
Author: User

Django Getting Started: http://www.nowamagic.net/academy/part/13/286


Install and build a project (website)

For additional information, there are several important commands:

django-admin.py startproject MySite: Build a project.

manage.py runserver: Start the MySite Web site that you just generated, and you can access it through http://127.0.0.1:8000/.


The MVC idea in the Django framework

Excerpt from: http://www.nowamagic.net/academy/detail/1318213

Let's look at a simple example where you can tell how the functionality implemented through the Web framework differs from the previous one. Here's an example of using Django to do the above: first, we split into 4 python files (models.py, views.py, urls.py) and HTML template files (latest_books.html).

models.py:

# models.py (the database tables) from

django.db Import Models

class book (Models. Model):
    name = models. Charfield (max_length=50)
    pub_date = models. Datefield ()

views.py:

# views.py (The business logic) from

django.shortcuts import Render_to_response to
models import book

def l Atest_books (Request):
    book_list = Book.objects.order_by ('-pub_date ') [: A] return
    render_to_response (' Latest_books.html ', {' book_list ': book_list})

urls.py:

# urls.py (the URL configuration) from

django.conf.urls.defaults Import *
import views

urlpatterns = Patterns (",
    (R ' ^latest/$ ', views.latest_books),
)

Latest_books.html:

# latest_books.html (the template)


Do not care about grammatical details, as long as the intention to feel the overall design. Only a few of the files that are split are focused here:

The models.py file mainly uses a Python class to describe the data table. Called model. Using this class, you can create, retrieve, update, and delete records in a database with simple Python code without having to write a single SQL statement.
The views.py file contains the business logic for the page. The Latest_books () function is called a view.
urls.py points out what kind of URL call view. In this example,/latest/url will call the Latest_books () function. In other words, if your domain name is example.com, anyone browsing the URL http://example.com/latest/will invoke the Latest_books () function.
Latest_books.html is an HTML template that describes how the page is designed. Use a template language with a basic logical declaration, such as {% for book in book_list%}

Combined, these loosely followed patterns are called model-view-controller (MVC). Simply put, MVC is a software development approach that separates code definitions from data access (models) to request logic (controllers) and user interfaces (views).
The key advantage of this design pattern is that the various components are loosely bound. In this way, each Django-driven Web application has a clear purpose and can be changed independently without affecting other parts. For example, a developer changes a URL in an application without affecting the implementation at the bottom of the program. Designers can change the style of HTML pages without touching the Python code. The database administrator can rename the datasheet and simply change one place without having to find and replace it from a large pile of files.


The view of MVC and the control part of Hello world

Excerpt from: http://www.nowamagic.net/academy/detail/1318235


A Django project contains files

Creating a directory using the Startproject command generates the following 4 files:

__init__.py: Let Python consider the directory as a file for a development package (that is, a set of modules). This is an empty file, generally you do not need to modify it.
manage.py: A command-line tool that allows you to interact with the Django project in a variety of ways. Type Python manage.py help to see what it can do. You should not need to edit this file; it is pure for convenience to build it in this directory.
settings.py: Setup or configuration of the Django project. View and understand the settings types and their default values available in this file.
Urls.py:Django the URL setting for the project. Visualize it as a directory for your Django site. At present, it is empty.
Although these files are small, these files already constitute a running Django application.

The first Django-based page: Hello World

As our first goal, create a Web page to output this famous sample message: Hello World (or Hello Nowamagic)
If you've ever posted the Hello World page, but didn't use the web frame, simply type Hello world into the hello.html text file and upload it to any Web server. Note that in this process, you have explained two key information about this page: it includes (the string "Hello World") and its URL (http://www.example.com/hello.html, if you put the file in a subdirectory, it may be http://www.example.com/files/hello.html).
With Django, you'll use different methods to illustrate that the contents of the page are generated by the view function (view functions), and the URL is defined in URLconf. First, we'll write a Hello world view function.
1. Make a View
First, we create an empty file called views.py in the MySite folder created by Startproject. That is, the __init__.py of these files in the same sibling directory.
This Python module will contain a view of this chapter. Please note that Django has no particular requirement for view.py's file naming, and it doesn't care what the file is called. But according to the Convention, it's a good idea to name it view.py, which will help other developers to read your code.

From django.http import HttpResponse

def hello (request): Return
    httpresponse ("Hello nowamagic")
OK, so simple, the view is done.
Let's analyze this code one line at a time:
First, we import the (import) HttpResponse class from the Django.http module. See the later appendix for more details on HttpRequest and HttpResponse. We need to import these classes, because we'll use them later.
Next, we define a view function called Hello.
Each view function must have at least one parameter, which is usually called request. This is an object that triggers the view, contains the current Web request information, and is an instance of the class Django.http.HttpRequest. In this example, although we don't need to do anything with the request, it must still be the first parameter of the view.
Note that the name of the view function is not important, and it does not have to be named in a certain way to allow Django to recognize it. Here we name it: Hello, because the name clearly shows the intent of the view. In the same way, you can name it with such an ugly phrase as: Hello_wonderful_beautiful_world. The next section (Your first URLconf) will tell you how Django found this function.
This function has a simple line of code: it simply returns a HttpResponse object that contains the text "Hello World".
The main point here is that a view is a function of Python. The type of the first argument for this function is HttpRequest; it returns a HttpResponse instance. To make a Python function a Django-recognizable view, it must meet both conditions. (There are exceptions, but we'll be in touch later.) )

2. Making URLconf
We have made the view before, and we need to explicitly tell it and activate the view through a URL that is described in detail. To bind the view functions and URLs, we use URLconf.
URLconf is like a directory of Web sites that Django supports. Its essence is the URL pattern and the mapping table between the view functions to be called for that URL pattern. That's the way you tell Django to call that code for this URL, and call that code for that URL. For example, when a user accesses/foo/, the View function Foo_view () is invoked, and the view function exists in the Python module file view.py.
The Startproject command will automatically build a URLconf (ie urls.py file) for you. The default urls.py will look like this:
From Django.conf.urls import patterns, include, url

# uncomment ' next two lines to enable ' admin:
# from Dja Ngo.contrib Import Admin
# admin.autodiscover ()

urlpatterns = Patterns (',
    # Examples:
    # URL (r ' ^$ ', ' PythonProject.views.home ', name= ' home '),
    # URL (r ' ^pythonproject/', include (' PythonProject.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/', include ( Admin.site.urls)),)
Let's make some changes to identify the URL to http://127.0.0.1:8000/hello/. It's easy to add a sentence like this:
(' ^hello/$ ', hello),
Now access http://127.0.0.1:8000/hello/, OK, successful display:
Hello Nowamagic

The default urlconf contains some of the commonly used features of the annotated Django, which can be turned on simply by removing the annotations. The following is the actual content of the annotated row that is omitted from the urlconf: from django.conf.urls.defaults import *

Urlpatterns = Patterns ("",

Let's explain the code step-by-step:

The first line imports all the modules under Django.conf.urls.defaults, which are the basic constructs of the Django urlconf. This contains a patterns function.
The second line calls the patterns () function and saves the returned result to the Urlpatterns variable. The patterns function currently has only one argument-an empty string. (This string can be used to represent a common prefix for a view function.) Specific we will introduce later. )
Current attention should be paid to the urlpatterns variable, and Django expects to find it from the root_urlconf module. The variable defines the mapping relationship between the URL and the code used to process the URLs. By default, URLconf All content is annotated--django application or Bai Zing piece.
In short, we just tell Django that all requests to url/hello/should be handled by the view function of Hello.
Here, we have created the first Django Web page. Task completed.


the model part of MVC and the ORM Hello World

Configure MySQL

Install Mysql-python: Slightly ...

Django connection MySQL, set settings.py, as follows:

DATABASES = {'
    default ': {'
        ENGINE ': ' Django.db.backends.mysql ', '
        NAME ': ' test111 ',
        ' USER ': ' Root ',
        ' PASSWORD ': ' 123456 ', ' 
        HOST ': ', 
        ' PORT ': ' 3306 '
    }
}
Where name is the name of the database to which you want to connect.

After saving, you can test whether the connection is correct in the Python shell
Python manage.py Shell
>>> from django.db Import connection
>>> cursor = Connection.cursor ()
If this step is not wrong, it means the connection is correct.







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.