Django learning Summary 3-view and url Configuration

Source: Internet
Author: User
Tags timedelta

I. Create a view

1. Create a new file named views. py in the mysite folder with the following content:


[Python]
From django. http import HttpResponse
 
Def hello (request)
Return HttpResponse ("Hello World ")

From django. http import HttpResponse

Def hello (request)
Return HttpResponse ("Hello World") each view function has at least one parameter, usually called request.

2. Modify the urls. py file and add the ing between the view function and url in views. py.


[Python]
From django. conf. urls. defaults import patterns, include, url
From mysite. views import hello
 
Urlpatterns = patterns ('',
('^ Hello/$', hello ),
)

From django. conf. urls. defaults import patterns, include, url
From mysite. views import hello

Urlpatterns = patterns ('',
('^ Hello/$', hello ),
) Add reference to this view function hello: from django. views import hello; Add the ing between the url and the view function: ('^ hello/$', hello). This is a tuples. The first part is a regular expression that specifies the url address, the second corresponds to the view function name. The upper arrow requires the expression to match the string header, and the dollar sign requires the expression to match the end of the string.


If we use a pattern '^ hello/' that is not at the end of $, any URL starting with/hello/will match, for example:/hello/foo and/hello/bar, not just/hello /. Similarly, if we ignore the tip (^), 'Hello/$ ', any URL Ending with hello/will match, for example: /foo/bar/hello /. If we simply use hello/, that is, there is no beginning with ^ and the end of $, then any URL containing hello/will match, such as:/foo/hello/bar. Therefore, we use these two symbols to ensure that only/hello/matches, not many.

3. Test

Running Server: python manange. py runserver

 

Ii. Regular Expressions

Symbol matching
. (Dot) any single character
\ D any Digit
[A-Z] any character from A to Z (uppercase)
[A-z] any character from a to z (lower case)
[A-Za-z] any character from a to z (Case Insensitive)
+ Match one or more (for example, \ d + matches one or more numeric characters)
[^/] + One or more characters not '/'
? Zero or a previous expression (for example, \ d? Matches zero or one number)
* Match 0 or more (for example, \ d * matches 0 or more numeric characters)
{1, 3} is an expression between one and three (inclusive) (for example, \ d {1, 3} matches one or two or three numbers)


Django's request processing process:

When creating a project with the django-admin.py startproject mysite, ROOT_URLCONF is automatically assigned:

ROOT_URLCONF = 'mysite. urls'


It will be used as URLconf to tell Django that Python modules will be used in this site.

1. When accessing URL/hello/, django loads URLconf according to the ROOT_URLCONF setting in setings. py.

2. Match URLpatterns one by one.

3. If the matching succeeds, the corresponding view function is called. The view function returns an HttpResponse

4. django converts HttpResponse to an appropriate HTTP response, which is displayed on a web page.

3. Dynamic Content

Displays the content of views. py at the current time dynamically.


[Python]
From django. http import HttpResponse
Import datetime
 
Def hello (request ):
Return HttpResponse ("Hello world ")
 
Def current_datetime (request ):
Now = datetime. datetime. now ()
Html = "Return HttpResponse (html)

From django. http import HttpResponse
Import datetime

Def hello (request ):
Return HttpResponse ("Hello world ")

Def current_datetime (request ):
Now = datetime. datetime. now ()
Html = "Return HttpResponse (html)
Urls. py content:


[Python]
From django. conf. urls. defaults import patterns, include, url
From mysite. views import hello, current_datetime
 
Urlpatterns = patterns ('',
('^ Hello/$', hello ),
('^ Datetime/$', current_datetime ),
)

From django. conf. urls. defaults import patterns, include, url
From mysite. views import hello, current_datetime

Urlpatterns = patterns ('',
('^ Hello/$', hello ),
('^ Datetime/$', current_datetime ),
) 4. Dynamic url

Method: use wildcards

Example: calculation time difference:

Add in urls. py


[Python]
(R' ^ time/plus/(\ d {1, 2})/$ ', current_datetime ),

(R' ^ time/plus/(\ d {1, 2})/$ ', current_datetime ),
The number represented by \ d. {1, 2} must be within two digits, that is, 0 ~ 99

R, indicating that the backslash is not needed.

To pass these numbers as parameters to the view function, enclose them in parentheses.

View functions:


[Python]
Def hours_ahead (request, offset ):
Try:
Offset = int (offset)
Failed t ValueError:
Raise Http404 ()
Dt = datetime. datetime. now () + datetime. timedelta (hours = offset)
Html = "Return HttpResponse (html)

Def hours_ahead (request, offset ):
Try:
Offset = int (offset)
Failed t ValueError:
Raise Http404 ()
Dt = datetime. datetime. now () + datetime. timedelta (hours = offset)
Html = "Return HttpResponse (html) we convert the offset captured from the url to the int type because the parameters captured by the url are always of the string type.

You can add the "assert False" trigger error page in the program and view Local vars to view Local variables. This is a debugging method.

 

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.