62. django MTV model (urls, view), djangourls

Source: Internet
Author: User
Tags install django

62. django MTV model (urls, view), djangourls

Today, we enter the most important stage of python. The django framework is like glue, which binds all the knowledge points we learned earlier, so you can see the previous essays for some vague information. This article describes the djangoMTV model, the URL Configuration System (URlconf) at the view layer, and the view functions (views) at the view layer ).

 

1. MTV Model

1. Main python frameworks:

Django: Big and complete

Flask: small but refined

2. Django's MTV

Model: database-related operations (ORM)

Template: Template syntax ---> How to skillfully embed variables (database data) into html pages

View: logical processing

In addition, Django also has a urls distributor: ing between paths and view functions.

3. Relationship Diagram

 

2. Basic django commands

1. Download

pip3 install django

2. Create a project

django-admin.py startproject mysite

Manage. py ----- A tool in the Django project that can call django shell and database.

Settings. py ---- contains the default settings of the project, including database information, debugging flag, and other working variables.

Urls. py ----- maps the URL mode to the application.

3. Create an application

python manage.py startapp blog

Models. py --- database-related operations.

Tests. py --- used for testing

Views. py --- used for write logic processing

4. Start the project

python manage.py runserver IP PORT

IP Address: the default local machine can be left empty

PORT: The default value is 8000.

 

3. View-layer routing configuration system (URlconf)

Function: Establishes the ing between url and view functions.

That is to say, tell Django to call this code for this URL, and call that code for that URL.

Basic Format:

'''Urlpatterns = [url (Regular Expression, views function, parameter, alias),] parameter description: a regular expression string, a callable object, it is usually an optional name parameter ''' for a view function or a string that specifies the path of the view function. The default parameter (in dictionary form) to be passed to the view function '''

1. Simple examples

From django. conf. urls import urlfrom project import viewsurlpatterns = [url (R' ^ articles/2003/$ ', views. special_case_2003), url (R' ^ articles/([0-9] {4})/([0-9] {2})/$ ', views. month_archive),]

Note:

''' Once the match is successful, it no longer matches the first url. to capture a value from the URL, you only need to place a pair of parentheses around it. You do not need to add a leading backslash because each URL has a backslash. For example, it should be ^ articles rather than ^/articles. The 'r' before each regular expression is optional, but we recommend that you add it. '''

2. Famous groups

1 url (R' ^ articles/(\ d {4})/(\ d {2}) $ ', views. year_month) # year (requset, 1990,12) by location parameter 2 famous group
Url (R' ^ articles /(? P <year> \ d {4 })/(? P <month> \ d {2}) $ ', views. year_month) # year (requset, year = 1990, month = 12) parameters are passed by position

3. search methods

In a http://www.example.com/myapp/ request, URLconf looks for myapp /.

In http://www.example.com/myapp? In the page = 3 Request, URLconf will still find myapp /.

URLconf does not check the request method. All request methods --> POST, GET, HEAD, etc. of the same URL --> route to the same function.

4. url Distribution

If there are too many applications in a project, resulting in too many coupling methods, we can use include to decouple and create a urls in each application.

Urls in the project:

from django.conf.urls import include, urlfrom django.contrib import adminurlpatterns = [   url(r'^admin/', admin.site.urls),   url(r'^blog/', include('blog.urls')),]

Urls in the application:

From django. conf. urls import urlimport viewsurlpatterns = [url (r '^ articles/2003/05 $', views. year_mon2), # year (requset, 1990,12) url (R' ^ articles /(? P <year> \ d {4 })/(? P <month> \ d {2}) $ ', views. year_month), # year (requset, year = 1990, month = 12) parameter by position]

5. pass additional options to the view function (understanding)

django.conf.urls.url()A function can receive an optional third parameter, which is a dictionary that indicates the additional keyword parameter that you want to pass to the view function.

from django.conf.urls import urlfrom . import viewsurlpatterns = [    url(r'^blog/(?P<year>[0-9]{4})/$', views.year_archive, {'foo': 'bar'}),]

In this example/blog/2005/Request, Django will callviews.year_archive(request, year='2005', foo='bar').

6,Reverse URL resolution (alias)

Example: the following URL (name)

from django.conf.urls import urlfrom django.contrib import adminfrom app1 import viewsurlpatterns = [    url(r'^admin/', admin.site.urls),    url(r'^$', views.login),    url(r'^login/', views.login,name="login")]

You can use the following method in the template code to obtain them (submit: action): (the template will be mentioned later)

<! DOCTYPE html> 

In this way, no errors will occur elsewhere when your matching rules and paths change.

IV,View functions (views) at the view layer)

1. SimpleView:

A view function (view for short) is used for logical processing. Is a simple Python function that accepts Web requests and returns Web responses.

1) The following is a view that returns the current date and time as an HTML document:

 

from django.http import HttpResponseimport datetimedef current_datetime(request):    now = datetime.datetime.now()    html = "

 

2) It must contain two objects:
Requset ----> request information
Httpresponse ----> response string

2. What data is contained in the request (key)

Request. GET: GET request data {} request. POST: Data in the POST request {} request. method: request method: When a GET or POST request has multiple values under a key: request. POST. getlist ("holobby") request. path: Request path request url: http: // 127.0.0.1: 8000/index.html/23? A = 1 request. path:/index.html/23 request. get_full_path () request url: http: // 127.0.0.1: 8000/index.html/23? A = 1 request. get_full_path ():/index.html/23? A = 1 COOKIES: standard Python dictionary objects that contain all cookies. Both keys and values are strings. FILES: Class dictionary object that contains all uploaded FILES. Each Key in FILES is the value of the name attribute in the <input type = "file" name = ""/> label, each value in FILES is also a standard python dictionary object, which contains the following three Keys: filename: Upload File Name, represented by a string, content_type: Content Type, content: user: the original content of the uploaded file. It is a django. contrib. auth. models. user object, representing the current login User. If the user is not logged on, the user will be initialized as the django. contrib. auth. models. AnonymousUser instance. You can use the is_authenticated () method of the user to identify whether the user logs in: if req. user. is_authenticated (); this attribute is available only when AuthenticationMiddleware in Django is activated: the unique read/write attribute, representing the dictionary object of the current session; this attribute is available only when you have enabled session support in Django.

3. Httpresponse Function

HttpReponse is a common class used to process returned results after the server receives a browser request. It is mainly used to return strings.

It is mandatory in every request, even if you use a render for example:

def render(request, template_name, context=None, content_type=None, status=None, using=None):    """    Returns a HttpResponse whose content is filled with the result of calling    django.template.loader.render_to_string() with the passed arguments.    """    content = loader.render_to_string(template_name, context, request, using=using)    return HttpResponse(content, content_type, status)

The internal function of render eventually returns HttpResponse.

4. render Function

Render (request, template_name [, context])

Combines a given template with a given context dictionary, and returns a rendered HttpResponse object.

Parameters:

Request: The request object used to generate the response.

Template_name: the complete name of the template to be used, an optional parameter (that is, the webpage we are talking about)

Context: a dictionary added to the template context. The default value is an empty dictionary. If a value in the dictionary is callable, the view will call it before rendering the template.

Content_type: MIME type to be used for the generated document. The default value is DEFAULT_CONTENT_TYPE.

Status: status Code of the response. The default value is 200.

def index(request):    name="yuan"    return render(request,"index.html",{"n":name})

5. redirect function (redirection)

The parameters can be:

A model: callsGet_absolute_url ()Function

A view with parameters:Urlresolvers. reverseTo reverse parse the name

An absolute or relative URL that uses the original block as the redirection location.

A temporary redirection is returned by default.Permanent = TrueReturns a permanent redirect.

def index(request):    return redirect("/login.html/")

The view function of login.html will be re-created from urlsand can also be directly written to the address for redirection.

6. Differences between render and resdirect

Render: only the page content is returned, but the second request is not sent, and the url is not refreshed. Therefore, after refreshing, the page will return to the previous page.

Redirect: the second request, url update

If the page requires template language rendering and the database data needs to be loaded to html, the render method will not display this part.

 

Note:

When using post requests, You Need To comment out a line of code in the settings. py configuration file.

MIDDLEWARE = ['django. middleware. security. securityMiddleware ', 'django. contrib. sessions. middleware. sessionMiddleware ', 'django. middleware. common. commonMiddleware ', # 'django. middleware. csrf. csrfViewMiddleware is the line 'django. contrib. auth. middleware. authenticationMiddleware ', 'django. contrib. messages. middleware. messageMiddleware ', 'django. middleware. clickjacking. XFrameOptionsMiddleware ',]

 

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.