Django---A powerful python web framework

Source: Internet
Author: User
Tags django web server

Django is a very powerful Web application framework for Python, and Django has the advantage of strong URL routing management, app management, background management, a full range of solutions (including session, cache, auth, templates, etc.), and very rich support documentation. Ideal for rapid development of MVC-based Web applications.

A Django project can contain multiple apps, using django-admin.py startproject myproject and django-admin.py Startapp MyApp1 to build project and app separately. Then, in the project's directory, execute the

Python manage.py runserver 0.0.0.0:8003 can start a Django Web server, such as.


As you can see, the new app can also be used in this way Python manage.py Startapp myApp2.

The hierarchical structure of the Django project is also very clear, with each app having its own directory.

1, configuration file

Home directory MyProject, or the main app directory, the settings.py file contains all the settings options for the Django project, such as

# project contains the app, here can be very convenient to do the management of the app, can be called hot Plug and unplug. Installed_apps = (    ' django.contrib.admin ',    ' Django.contrib.auth ',    ' django.contrib.contenttypes ',    ' django.contrib.sessions ',    ' django.contrib.messages ',    ' django.contrib.staticfiles ',)

# root_urlconf is the root route file for the Django project, which determines all the routing configuration rules. root_urlconf = ' myproject.urls ' # template settings, set directory for Web front-end Templates Template_dirs = (    ' myproject/templates ',) # Static Files (CSS, JavaScript, Images) Static_url = '/static/' staticfiles_dirs = (    os.path.join (base_dir, ' STATIC '). Replace (' \ \ ', '/'),)

# database Settings databases = {'    default ': {        ' ENGINE ': ' Django.db.backends.mysql ',        ' NAME ': ' mydb1 ',        ' USER ': ' mydb1 ', '        PASSWORD ': ' 123456 ',        ' HOST ': ' 192.168.5.126 ',        ' PORT ': 3306,        ' OPTIONS ': {              ' CharSet ': ' UTF8 ',              ' use_unicode ': True,        },    },}

The above is the content of the settings.py configuration file for this Django project.

2, routing rules

The routing rules that Django uses are very elegant, and each app has its own separate urls.py file to manage these rules. The format is as follows:

Urlpatterns = Patterns ("",    url (r ' ^index/$ ', views.index),    url (r ' ^result/', include (' Result.urls ')),)
The rules of the URL are matched by regular expressions, and the URL (r ' ^index/$ ', views.index) represents a link to the R ' ^index/$ ' matching rule, pointing to the index method below views.py.

The URL (r ' ^result/', include (' Result.urls ')) represents a link that conforms to the R ' ^result/' matching rule and is then searched for in the urls.py routing file under another app result. Find the principle above.

From Django.conf.urls import patterns, include, urlurlpatterns = Patterns (' result.views ',    url (r ' ^queryresults/$ ', ' QueryResults '),    url (r ' ^moreresults/$ ', ' moreresults '),)

3, view views

As for the specifics of the routing rules, they are all included in the file views.py. This is also where the MVC framework features very clearly.
From django.shortcuts Import renderdef Index (Request):    return render (Request, ' index.html ')
The index method will find index.html from the template directory and render it to the browser.

The following QueryResults method, which can be used to link a GET request, is to query the result from the database and return it to the browser.

def QueryResults (Request):    '    @desc: QueryResults    '    if Request.method = = ' GET ':        if Request.session.has_key ("userid"):            data = Resultserializer (Result.objects.filter (                user=request.session[' UserID ']) [0:10], many=true). Data            data = Jsonrenderer (). Render (data)            return HttpResponse (Json.dumps ({" Status ": 0," Data ": Data}),                    content_type=" Application/json ")        else:            return HttpResponse (Json.dumps ({" Status ": 1,                    " err_msg ":" Can not find the user info "}),                    content_type=" Application/json ")    else:        Return HttpResponse (Json.dumps ({"Status": 1,                "err_msg": "It only has support HTTP GET method."}),                content_type= " Application/json ")
In this way, links on the Web page can be presented in a very elegant manner through urls.py, views.py, and the app of the Django Project.
4, Template templates

The template directory contains all the HTML files. Where {% load staticfiles%} is the Django syntax, which is to load the files in the Staticfiles directory.

(Staticfiles is set in the settings.py file, ' Django.contrib.staticfiles ', which corresponds to the directory that the Staticfiles_dirs variable in the settings.py refers to)

{% load Staticfiles%}<! DOCTYPE html>
Static directory, used to store the project required CSS, JS and other resource files.

A similar Django syntax is:

{% extends "base.html"%} {% block content%}<div id= "faq-tab-1" class= "Tab-pane Fade" >{% include "results.html"%}</div>{% endblock%}
The role is to make the div a block named content, and then the block can be referenced elsewhere in the HTML file. The reference method is {% block content%}{% endblock%}.

Well, the basic structure of the Django web framework is introduced here. You are welcome to correct me.

Other very useful modules of Django will be introduced in subsequent blogs.







Django---A powerful python web framework

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.