Web Development Django (a basic article)

Source: Internet
Author: User
Tags http post sqlite database python mysql



What is a web framework?

Framework, which is a constrained support structure designed to solve an open problem, uses a framework to help you develop a specific system quickly,
To put it simply, you use someone else's set-up stage to perform. For, all Web applications, in essence, is actually a socket server, the user's browser actually
is a socket client.

############################################################################################


Basic Configuration
First, create a Django program
Terminal command: Django-admin startproject sitename
When the IDE creates a Django program, it is essentially automating the above command
Other common commands:
Python manage.py runserver 0.0.0.0
Python manage.py Startapp AppName
Python manage.py syncdb
Python manage.py makemigrations
Python manage.py Migrate
Python manage.py Createsuperuser

Second, static files

Staticfiles_dirs = (
Os.path.join (Base_dir, ' static '),
)


MVC and MTV modes:

The famous MVC pattern: the so-called MVC is to divide Web applications into models (M), controllers (C), view (V) Three layers, and they are connected together in a plug-in, loosely coupled way.
The model is responsible for the business object with the database object (ORM), the view is responsible for interacting with the user (page), the controller (C) accepts the user's input call model and the view completes the user's request.

The Django MTV model is essentially no different from the MVC pattern, and it's just a little different from the definition of each component in order to remain loosely coupled, as Django's MTV represents:
Model: Object that is responsible for business objects and databases (ORM)
Template (Template): Responsible for how to display the page to the user
View: Responsible for business logic, and call model and template when appropriate
In addition, Django has a URL dispatcher that distributes page requests for URLs to different view processes, and then calls the corresponding model and template



One, Django URL (routing system)

The URL configuration (URLconf) is like the directory of the Web site that Django supports. Its essence is the URL pattern and the mapping table between the view functions to be called for the URL pattern;
That's how you tell Django to call that code for that URL and call that code for that URL.

1 Urlpatterns = [
2 URL (regular expression, views view function, parameter, alias),
6 8

Parameter description:

A regular expression string
A callable object, typically a view function or a string that specifies the path of a view function
Optional default parameters to pass to the view function (in dictionary form)
An optional name parameter

URL instance:

From Django.conf.urls import URL
From Django.contrib Import admin
From APP01 Import views

Urlpatterns = [

URL (r ' ^articles/2003/$ ', views.special_case_2003),

#url (R ' ^articles/[0-9]{4}/$ ', views.year_archive),

URL (r ' ^articles/([0-9]{4})/$ ', views.year_archive), #no_named Group

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),

]

From Django.conf.urls import URL
From APP01 Import views

Urlpatterns = [
URL (r ' ^articles/2003/$ ', views.special_case_2003),
URL (r ' ^articles/(? P<YEAR>[0-9]{4})/$ ', views.year_archive),
URL (r ' ^articles/(? P<YEAR>[0-9]{4})/(? P<MONTH>[0-9]{2})/$ ', views.month_archive),
URL (r ' ^articles/(? P<YEAR>[0-9]{4})/(? P<MONTH>[0-9]{2})/(? P<DAY>[0-9]{2})/$ ', Views.article_detail),
]



Second, the configuration of the models database

1 Django supports Sqlite,mysql, Oracle,postgresql database by default.
Django uses SQLite's database by default, default with SQLite database driver, engine name: Django.db.backends.sqlite3

2 MySQL Driver
MySQLdb (MySQL python)
Mysqlclient
Mysql
Pymysql (pure python mysql driver)

3 The SQLite database is used by default in Django projects, with the following settings in Settings:
If we want to change the database, we need to modify the following:
databases={
' Default ': {
' ENGINE ': ' Django.db.backends.mysql ',
' NAME ': ' Django ' _com ',
' USER ': ' Root ',
' PASSWORD ': ' PASSWORD ',
' HOST ': ' ... ',
"PORT": ' ... ',
}
}



Third, template Foundation (introduction of formwork system)

The composition of the template
Composition: HTML code + logic control code

Composition of logical control code
1 variables (using double curly braces to refer to variables): {{var_name}}
Search for depth variables (Universal period number)

2 Use of tags (using a combination of curly braces and percentages to indicate the use of tag)

Use of {% if%}:
The {% if%} tag calculates a variable value, if it is "true", that is, it exists, is not NULL, and is not a Boolean value of false, the system displays all contents between {% if%} and {% endif%}
{% if num >= and 8}

{% if num > 200}
<p>num Greater than 200</p>
{% Else%}
<p>num greater than 100 less than 200</p>
{% ENDIF%}

{% elif num < 100%}
<p>num less than 100</p>

{% Else%}
<p>num equals 100</p>.

{% ENDIF%}


{% for%} use
The {% for%} tag allows you to iterate through each element in a sequence sequentially, rendering all content between {% for%} and {% endfor%} per cycle of the template system
< ul >
{%for obj in list%}
< li > {{obj.name}} </li >
{% ENDFOR%}
</ul >


{%csrf_token%}:csrf_token Tags
tags used to generate Csrf_token for cross-site attack verification. Note that if you use the Render_to_response method in the view index, it will not take effect.
In fact, this will generate an input tag that is submitted to the background along with other form labels.


{% URL%}: Address referring to routing configuration

{% with%}: Replace complex variable names with simpler variable names
{% with total=fhjsaldfhjsdfhlasdfhljsdal%} {{Total}} {% Endwith%}

{% VERBATIM%}: no render

{% load%}: Load Tag Library


3 Customizing the filter and Simple_tag
A. Create the Templatetags module in the app (required)
b, create any. py file, such as: my_tags.py
C, import the previously created my_tags.py in an HTML file that uses custom Simple_tag and filter: {% load my_tags%}
D, using Simple_tag and filter (How to call)
E, Installed_apps in Settings Configure the current app, or Django cannot find the custom Simple_tag.
From Django Import Template
From django.utils.safestring import Mark_safe

Register = template. Library () #register的名字是固定的, cannot be changed


@register. Filter
def filter_multi (V1,V2):
Return V1 * v2


@register. Simple_tag
def simple_tag_multi (V1,V2):
Return V1 * v2


@register. Simple_tag
def my_input (Id,arg):
result = "<input type= ' text ' id= '%s ' class= '%s '/>"% (Id,arg,)
return Mark_safe (Result)


-------------------------------. html
{% load xxx%} # first line

# num=12
{{num | filter_multi:2}} # 24

{{num | filter_multi: ' [22,333,4444] '}}

{% Simple_tag_multi 2 5} parameter is not limited, but cannot be placed in the IF for statement
{% Simple_tag_multi num 5}


4 Extend Template inheritance
{% extends "base.html"%}

{% block title%}
The current time
{% Endblock%}

{% block content%}
< p > It's now {{current_date}}. </p >
{% Endblock%}




Four, Views (view function)

HttpResponse: Passes in a data, returns a string
Render (Request, "xxx.html", {"obj": Xx_ "List"}
1. Find HTML template, open function to get to memory
2. Django Template engine: HTML template content + data = render (replace) = = = Final String
3. HttpResponse (Final String)
Redirect: page jumps.

Request requests (properties and methods of the request object):

Path: The full path of the requested page, excluding the domain name
Method: The string representation of the HTTP method used in the request. All uppercase.
GET: Class Dictionary object containing all HTTP GET parameters
POST: Class Dictionary object with all HTTP POST parameters
Cookies: A standard Python Dictionary object containing all cookies; keys and values are strings.
Session: The only read-write property that represents the current session's Dictionary object, which is only available if you have activated the session support in Django.
Files: A class Dictionary object that contains all the uploaded files;

Web Development Django (a basic 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.