SlideShare a Scribd company logo
1 of 11
Download to read offline
The	
  Django	
  Book	
  
Chapter	
  3:	
  Views	
  and	
  URLconfs	
  
	
  
Speaker:	
  Vincent	
  Chien	
  
Introduction	
  
•  Views:	
  The	
  main	
  lesson	
  here	
  is	
  this:	
  a	
  view	
  is	
  just	
  a	
  Python	
  
funcAon	
  that	
  takes	
  an	
  HCpRequest	
  as	
  its	
  first	
  parameter	
  and	
  
returns	
  an	
  instance	
  of	
  HCpResponse.	
  
	
  
	
  
	
  
•  URLConfs:	
  To	
  hook	
  a	
  view	
  funcAon	
  to	
  a	
  parAcular	
  URL	
  with	
  
Django,	
  use	
  a	
  URLconf.	
  
	
  
	
  
	
  
	
  
•  Loose	
  Coupling(鬆散耦合):	
  changes	
  made	
  to	
  one	
  of	
  the	
  
pieces	
  will	
  have	
  liCle	
  or	
  no	
  effect	
  on	
  the	
  other.	
  
view function, and the URL is specified in a URLconf. First, let’s write our “Hello world” view function.
4.1.1 Your First View
Within the mysite directory that django-admin.py startproject made in the last chapter, create an em
file called views.py. This Python module will contain our views for this chapter. Note that there’s nothing spe
about the name views.py – Django doesn’t care what the file is called, as you’ll see in a bit – but it’s a good ide
call it views.py as a convention, for the benefit of other developers reading your code.
Our “Hello world” view is simple. Here’s the entire function, plus import statements, which you should type into
views.py file:
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello world")
Let’s step through this code one line at a time:
• First, we import the class HttpResponse, which lives in the django.http module. We need to import
class because it’s used later in our code.
• Next, we define a function called hello – the view function.
Each view function takes at least one parameter, called request by convention. This is an object that
tains information about the current Web request that has triggered this view, and it’s an instance of the c
Django Book Documentation, Release 0.1
Let’s step through this code one line at a time:
• The first line imports all objects from the django.conf.urls.defaults module, which is Django’s
URLconf infrastructure. This includes a function called patterns.
• The second line calls the function patterns and saves the result into a variable called urlpatterns. The
patterns function gets passed only a single argument – the empty string. (The string can be used to supply a
common prefix for view functions, which we’ll cover in Chapter 8.)
The main thing to note here is the variable urlpatterns, which Django expects to find in your URLconf module.
This variable defines the mapping between URLs and the code that handles those URLs. By default, as we can see,
the URLconf is empty – your Django application is a blank slate. (As a side note, that’s how Django knew to show
you the “Welcome to Django” page in the last chapter. If your URLconf is empty, Django assumes you just started a
new project and, hence, displays that message.)
To add a URL and view to the URLconf, just add a Python tuple mapping a URL pattern to the view function. Here’s
how to hook in our hello view:
from django.conf.urls.defaults import *
from mysite.views import hello
urlpatterns = patterns(’’,
(’^hello/$’, hello),
)
(Note that we’ve removed the commented-out code for brevity. You can choose to leave those lines in, if you’d like.)
We made two changes here:
• First, we imported the hello view from its module – mysite/views.py, which translates into
mysite.views in Python import syntax. (This assumes mysite/views.py is on your Python path; see
the sidebar for details.)
How	
  Django	
  Process	
  a	
  Request	
  
•  A	
  request	
  comes	
  in	
  to	
  /hello/.	
  
•  Django	
  determines	
  the	
  root	
  URLconf	
  by	
  looking	
  at	
  the	
  
ROOT_URLCONF	
  seTng.	
  
•  Django	
  looks	
  at	
  all	
  of	
  the	
  URLpaCerns	
  in	
  the	
  URLconf	
  for	
  the	
  first	
  
one	
  that	
  matches	
  /hello/.	
  
•  If	
  it	
  finds	
  a	
  match,	
  it	
  calls	
  the	
  associated	
  view	
  funcAon.	
  
•  The	
  view	
  funcAon	
  returns	
  an	
  HCpResponse.	
  
•  Django	
  converts	
  the	
  HCpResponse	
  to	
  the	
  proper	
  HTTP	
  response,	
  
which	
  results	
  in	
  a	
  Web	
  page.	
  
you the “Welcome to Django” page in the last chapter. If your URLconf is empty,
new project and, hence, displays that message.)
To add a URL and view to the URLconf, just add a Python tuple mapping a URL p
how to hook in our hello view:
from django.conf.urls.defaults import *
from mysite.views import hello
urlpatterns = patterns(’’,
(’^hello/$’, hello),
)
(Note that we’ve removed the commented-out code for brevity. You can choose to
We made two changes here:
• First, we imported the hello view from its module – mysite/v
mysite.views in Python import syntax. (This assumes mysite/view
the sidebar for details.)
• Next, we added the line (’^hello/$’, hello), to urlpatterns. T
tern. It’s a Python tuple in which the first element is a pattern-matching str
this in a bit) and the second element is the view function to use for that patte
In a nutshell, we just told Django that any request to the URL /hello/ shoul
function.
Your Python Path
Your Python path is the list of directories on your system where Python looks w
URLconf	
  feature	
  
•  URLconf	
  passed	
  view	
  funciton	
  as	
  an	
  object	
  without	
  calling	
  the	
  
funciton.	
  This	
  is	
  a	
  key	
  feature	
  of	
  Python(and	
  other	
  dynamic	
  
languages):	
  funcitons	
  are	
  first-­‐class	
  objects,	
  which	
  means	
  you	
  
can	
  pass	
  them	
  around	
  just	
  like	
  any	
  other	
  variables.	
  
hCp://swaywang.blogspot.tw/2012/01/first-­‐class-­‐funcAon.html	
  
Regular	
  Expressions(1/2)	
  
•  caret(	
  ^	
  ):	
  require	
  that	
  the	
  paCern	
  matches	
  the	
  start	
  of	
  the	
  
string.	
  
•  dollar	
  sign(	
  $	
  ):	
  require	
  that	
  the	
  paCern	
  matches	
  the	
  end	
  of	
  
the	
  string.	
  
Regular	
  Expressions(2/2)	
  
hCp://en.wikipedia.org/wiki/Regular_expression	
  
	
  
	
  
Django Book Documentation, Release 0.1
Symbol Matches
. (dot) Any single character
d Any single digit
[A-Z] Any character between A and Z (uppercase)
[a-z] Any character between a and z (lowercase)
[A-Za-z] Any character between a and z (case-insensitive)
+ One or more of the previous expression (e.g., d+ matches one or more digits)
[^/]+ One or more characters until (and not including) a forward slash
? Zero or one of the previous expression (e.g., d? matches zero or one digits)
* Zero or more of the previous expression (e.g., d* matches zero, one or more than one
digit)
{1,3} Between one and three (inclusive) of the previous expression (e.g., d{1,3} matches
one, two or three digits)
For more on regular expressions, see http://www.djangoproject.com/r/python/re-module/.
4.1.3 A Quick Note About 404 Errors
At this point, our URLconf defines only a single URLpattern: the one that handles requests to the URL /hello/.
What happens when you request a different URL?
To find out, try running the Django development server and visiting a page such as
http://127.0.0.1:8000/goodbye/ or http://127.0.0.1:8000/hello/subdirectory/,
or even http://127.0.0.1:8000/ (the site “root”). You should see a “Page not found” message (see Figure
regex	
  example	
  
•  '^hello/’	
  
/hello/foo	
  
/hello/bar	
  
	
  
•  ‘hello/$’	
  
/foo/bar/hello/	
  
	
  
•  ‘hello/‘	
  
/foo/hello/bar	
  
	
  
•  r'^Ame/plus/d+/$’	
  
r'^Ame/plus/d{1,2}/$’	
  
	
  
	
  
raw	
  string	
  
r'n’	
  !=	
  ‘n’	
  
Dynamic	
  URLs	
  
•  Query	
  string	
  parameter	
  is	
  a	
  method.	
  
•  But	
  Django’s	
  URLconf	
  system	
  encourages	
  preCy	
  URLs.	
  
•  r'^Ame/plus/d+/$'	
  
•  r'^Ame/plus/d{1,2}/$'	
  
Python’s usage of backslashes and the backslashes that are found in regular expressions, so it’s s
you use raw strings any time you’re defining a regular expression in Python. From now on, all
this book will be raw strings.
Now that we’ve designated a wildcard for the URL, we need a way of passing that wildcard dat
so that we can use a single view function for any arbitrary hour offset. We do this by placing p
data in the URLpattern that we want to save. In the case of our example, we want to save whatev
in the URL, so let’s put parentheses around the d{1,2}, like this:
(r’^time/plus/(d{1,2})/$’, hours_ahead),
If you’re familiar with regular expressions, you’ll be right at home here; we’re using parenthese
the matched text.
The final URLconf, including our previous two views, looks like this:
from django.conf.urls.defaults import *
from mysite.views import hello, current_datetime, hours_ahead
urlpatterns = patterns(’’,
(r’^hello/$’, hello),
(r’^time/$’, current_datetime),
(r’^time/plus/(d{1,2})/$’, hours_ahead),
)
With that taken care of, let’s write the hours_ahead view.
Coding Order
Dynamic	
  URLs	
  
Django Book Documentation, Release 0.1
from django.http import Http404, HttpResponse
import datetime
def hours_ahead(request, offset):
try:
offset = int(offset)
except ValueError:
raise Http404()
dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt)
return HttpResponse(html)
Let’s step through this code one line at a time:
• The view function, hours_ahead, takes two parameters: request and offset.
– request is an HttpRequest object, just as in hello and current_datetime. We’ll say it again:
each view always takes an HttpRequest object as its first parameter.
– offset is the string captured by the parentheses in the URLpattern. For example, if the requested
URL were /time/plus/3/, then offset would be the string ’3’. If the requested URL were
/time/plus/21/, then offset would be the string ’21’. Note that captured values will always
Debug	
  suggestion	
  
•  assert	
  False	
  
Below the “Request information” section, the “Settings” section lists all of the settings for this particular Django
installation. (We’ve already mentioned ROOT_URLCONF, and we’ll show you various Django settings through-
out the book. All the available settings are covered in detail in Appendix D.)
The Django error page is capable of displaying more information in certain special cases, such as the case of template
syntax errors. We’ll get to those later, when we discuss the Django template system. For now, uncomment the offset
= int(offset) lines to get the view function working properly again.
Are you the type of programmer who likes to debug with the help of carefully placed print statements? You can use
the Django error page to do so – just without the print statements. At any point in your view, temporarily insert an
assert False to trigger the error page. Then, you can view the local variables and state of the program. Here’s an
example, using the hours_ahead view:
def hours_ahead(request, offset):
try:
offset = int(offset)
except ValueError:
raise Http404()
dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
assert False
html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt)
return HttpResponse(html)
Finally, it’s obvious that much of this information is sensitive – it exposes the innards of your Python code and Django
configuration – and it would be foolish to show this information on the public Internet. A malicious person could use
it to attempt to reverse-engineer your Web application and do nasty things. For that reason, the Django error page is
only displayed when your Django project is in debug mode. We’ll explain how to deactivate debug mode in Chapter
12. For now, just know that every Django project is in debug mode automatically when you start it. (Sound familiar?
The “Page not found” errors, described earlier in this chapter, work the same way.)
4.7 What’s next?
So far, we’ve been writing our view functions with HTML hard-coded directly in the Python code. We’ve done that to
keep things simple while we demonstrated core concepts, but in the real world, this is nearly always a bad idea.

More Related Content

What's hot

JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
Introduction to Python decorators
Introduction to Python decoratorsIntroduction to Python decorators
Introduction to Python decoratorsrikbyte
 
PyCon NZ 2013 - Advanced Methods For Creating Decorators
PyCon NZ 2013 - Advanced Methods For Creating DecoratorsPyCon NZ 2013 - Advanced Methods For Creating Decorators
PyCon NZ 2013 - Advanced Methods For Creating DecoratorsGraham Dumpleton
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2José Paumard
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherBlue Elephant Consulting
 
Java SE 8 for Java EE developers
Java SE 8 for Java EE developersJava SE 8 for Java EE developers
Java SE 8 for Java EE developersJosé Paumard
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerMario Fusco
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsBrian Moschel
 
The Django Book chapter 4 templates (supplement)
The Django Book chapter 4 templates (supplement)The Django Book chapter 4 templates (supplement)
The Django Book chapter 4 templates (supplement)Vincent Chien
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1José Paumard
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web ModuleMorgan Cheng
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
 
Java SE 8 for Java EE developers
Java SE 8 for Java EE developersJava SE 8 for Java EE developers
Java SE 8 for Java EE developersJosé Paumard
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingMario Fusco
 

What's hot (20)

JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Introduction to Python decorators
Introduction to Python decoratorsIntroduction to Python decorators
Introduction to Python decorators
 
PyCon NZ 2013 - Advanced Methods For Creating Decorators
PyCon NZ 2013 - Advanced Methods For Creating DecoratorsPyCon NZ 2013 - Advanced Methods For Creating Decorators
PyCon NZ 2013 - Advanced Methods For Creating Decorators
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Java SE 8 for Java EE developers
Java SE 8 for Java EE developersJava SE 8 for Java EE developers
Java SE 8 for Java EE developers
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Free your lambdas
Free your lambdasFree your lambdas
Free your lambdas
 
Computer Science Homework Help
Computer Science Homework HelpComputer Science Homework Help
Computer Science Homework Help
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
The Django Book chapter 4 templates (supplement)
The Django Book chapter 4 templates (supplement)The Django Book chapter 4 templates (supplement)
The Django Book chapter 4 templates (supplement)
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
Functions
FunctionsFunctions
Functions
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Java SE 8 for Java EE developers
Java SE 8 for Java EE developersJava SE 8 for Java EE developers
Java SE 8 for Java EE developers
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 

Viewers also liked

Django getting start
Django getting startDjango getting start
Django getting startshengwu83
 
Font End Development + Automation with Django
Font End Development + Automation with DjangoFont End Development + Automation with Django
Font End Development + Automation with DjangoEvan Reiser
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with DjangoSimon Willison
 
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Samuel Fortier-Galarneau
 
Django class based views for beginners
Django class based views for beginnersDjango class based views for beginners
Django class based views for beginnersSpin Lai
 
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 MinutesDjangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 MinutesNina Zakharenko
 
Djangocon 2014 angular + django
Djangocon 2014 angular + djangoDjangocon 2014 angular + django
Djangocon 2014 angular + djangoNina Zakharenko
 
Create responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSCreate responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSHannes Hapke
 

Viewers also liked (9)

Django getting start
Django getting startDjango getting start
Django getting start
 
Font End Development + Automation with Django
Font End Development + Automation with DjangoFont End Development + Automation with Django
Font End Development + Automation with Django
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
 
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
 
Django class based views for beginners
Django class based views for beginnersDjango class based views for beginners
Django class based views for beginners
 
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 MinutesDjangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
 
Djangocon 2014 angular + django
Djangocon 2014 angular + djangoDjangocon 2014 angular + django
Djangocon 2014 angular + django
 
Create responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSCreate responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJS
 
RESTful API Design, Second Edition
RESTful API Design, Second EditionRESTful API Design, Second Edition
RESTful API Design, Second Edition
 

Similar to The Django Book / Chapter 3: Views and URLconfs

WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptxWRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptxsalemsg
 
Akash rajguru project report sem v
Akash rajguru project report sem vAkash rajguru project report sem v
Akash rajguru project report sem vAkash Rajguru
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath Shenoy
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial之宇 趙
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting startedMoniaJ
 
Rapid web application development using django - Part (1)
Rapid web application development using django - Part (1)Rapid web application development using django - Part (1)
Rapid web application development using django - Part (1)Nishant Soni
 
Django tutorial
Django tutorialDjango tutorial
Django tutorialKsd Che
 
Chapter 8- Advanced Views and URLconfs
Chapter 8- Advanced Views and URLconfsChapter 8- Advanced Views and URLconfs
Chapter 8- Advanced Views and URLconfsVincent Chien
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014Matthias Noback
 
Angular custom directives
Angular custom directivesAngular custom directives
Angular custom directivesAlexe Bogdan
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumMatthias Noback
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular IntermediateLinkMe Srl
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIEric Wise
 
The Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaThe Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaMatthias Noback
 

Similar to The Django Book / Chapter 3: Views and URLconfs (20)

Django by rj
Django by rjDjango by rj
Django by rj
 
templates in Django material : Training available at Baabtra
templates in Django material : Training available at Baabtratemplates in Django material : Training available at Baabtra
templates in Django material : Training available at Baabtra
 
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptxWRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
 
Akash rajguru project report sem v
Akash rajguru project report sem vAkash rajguru project report sem v
Akash rajguru project report sem v
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
 
DJango
DJangoDJango
DJango
 
Rapid web application development using django - Part (1)
Rapid web application development using django - Part (1)Rapid web application development using django - Part (1)
Rapid web application development using django - Part (1)
 
Django
DjangoDjango
Django
 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
 
Chapter 8- Advanced Views and URLconfs
Chapter 8- Advanced Views and URLconfsChapter 8- Advanced Views and URLconfs
Chapter 8- Advanced Views and URLconfs
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014
 
Angular custom directives
Angular custom directivesAngular custom directives
Angular custom directives
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup Belgium
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular Intermediate
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPI
 
The Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaThe Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony Barcelona
 

Recently uploaded

Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 

Recently uploaded (20)

Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 

The Django Book / Chapter 3: Views and URLconfs

  • 1. The  Django  Book   Chapter  3:  Views  and  URLconfs     Speaker:  Vincent  Chien  
  • 2. Introduction   •  Views:  The  main  lesson  here  is  this:  a  view  is  just  a  Python   funcAon  that  takes  an  HCpRequest  as  its  first  parameter  and   returns  an  instance  of  HCpResponse.         •  URLConfs:  To  hook  a  view  funcAon  to  a  parAcular  URL  with   Django,  use  a  URLconf.           •  Loose  Coupling(鬆散耦合):  changes  made  to  one  of  the   pieces  will  have  liCle  or  no  effect  on  the  other.   view function, and the URL is specified in a URLconf. First, let’s write our “Hello world” view function. 4.1.1 Your First View Within the mysite directory that django-admin.py startproject made in the last chapter, create an em file called views.py. This Python module will contain our views for this chapter. Note that there’s nothing spe about the name views.py – Django doesn’t care what the file is called, as you’ll see in a bit – but it’s a good ide call it views.py as a convention, for the benefit of other developers reading your code. Our “Hello world” view is simple. Here’s the entire function, plus import statements, which you should type into views.py file: from django.http import HttpResponse def hello(request): return HttpResponse("Hello world") Let’s step through this code one line at a time: • First, we import the class HttpResponse, which lives in the django.http module. We need to import class because it’s used later in our code. • Next, we define a function called hello – the view function. Each view function takes at least one parameter, called request by convention. This is an object that tains information about the current Web request that has triggered this view, and it’s an instance of the c Django Book Documentation, Release 0.1 Let’s step through this code one line at a time: • The first line imports all objects from the django.conf.urls.defaults module, which is Django’s URLconf infrastructure. This includes a function called patterns. • The second line calls the function patterns and saves the result into a variable called urlpatterns. The patterns function gets passed only a single argument – the empty string. (The string can be used to supply a common prefix for view functions, which we’ll cover in Chapter 8.) The main thing to note here is the variable urlpatterns, which Django expects to find in your URLconf module. This variable defines the mapping between URLs and the code that handles those URLs. By default, as we can see, the URLconf is empty – your Django application is a blank slate. (As a side note, that’s how Django knew to show you the “Welcome to Django” page in the last chapter. If your URLconf is empty, Django assumes you just started a new project and, hence, displays that message.) To add a URL and view to the URLconf, just add a Python tuple mapping a URL pattern to the view function. Here’s how to hook in our hello view: from django.conf.urls.defaults import * from mysite.views import hello urlpatterns = patterns(’’, (’^hello/$’, hello), ) (Note that we’ve removed the commented-out code for brevity. You can choose to leave those lines in, if you’d like.) We made two changes here: • First, we imported the hello view from its module – mysite/views.py, which translates into mysite.views in Python import syntax. (This assumes mysite/views.py is on your Python path; see the sidebar for details.)
  • 3. How  Django  Process  a  Request   •  A  request  comes  in  to  /hello/.   •  Django  determines  the  root  URLconf  by  looking  at  the   ROOT_URLCONF  seTng.   •  Django  looks  at  all  of  the  URLpaCerns  in  the  URLconf  for  the  first   one  that  matches  /hello/.   •  If  it  finds  a  match,  it  calls  the  associated  view  funcAon.   •  The  view  funcAon  returns  an  HCpResponse.   •  Django  converts  the  HCpResponse  to  the  proper  HTTP  response,   which  results  in  a  Web  page.   you the “Welcome to Django” page in the last chapter. If your URLconf is empty, new project and, hence, displays that message.) To add a URL and view to the URLconf, just add a Python tuple mapping a URL p how to hook in our hello view: from django.conf.urls.defaults import * from mysite.views import hello urlpatterns = patterns(’’, (’^hello/$’, hello), ) (Note that we’ve removed the commented-out code for brevity. You can choose to We made two changes here: • First, we imported the hello view from its module – mysite/v mysite.views in Python import syntax. (This assumes mysite/view the sidebar for details.) • Next, we added the line (’^hello/$’, hello), to urlpatterns. T tern. It’s a Python tuple in which the first element is a pattern-matching str this in a bit) and the second element is the view function to use for that patte In a nutshell, we just told Django that any request to the URL /hello/ shoul function. Your Python Path Your Python path is the list of directories on your system where Python looks w
  • 4. URLconf  feature   •  URLconf  passed  view  funciton  as  an  object  without  calling  the   funciton.  This  is  a  key  feature  of  Python(and  other  dynamic   languages):  funcitons  are  first-­‐class  objects,  which  means  you   can  pass  them  around  just  like  any  other  variables.   hCp://swaywang.blogspot.tw/2012/01/first-­‐class-­‐funcAon.html  
  • 5. Regular  Expressions(1/2)   •  caret(  ^  ):  require  that  the  paCern  matches  the  start  of  the   string.   •  dollar  sign(  $  ):  require  that  the  paCern  matches  the  end  of   the  string.  
  • 6. Regular  Expressions(2/2)   hCp://en.wikipedia.org/wiki/Regular_expression       Django Book Documentation, Release 0.1 Symbol Matches . (dot) Any single character d Any single digit [A-Z] Any character between A and Z (uppercase) [a-z] Any character between a and z (lowercase) [A-Za-z] Any character between a and z (case-insensitive) + One or more of the previous expression (e.g., d+ matches one or more digits) [^/]+ One or more characters until (and not including) a forward slash ? Zero or one of the previous expression (e.g., d? matches zero or one digits) * Zero or more of the previous expression (e.g., d* matches zero, one or more than one digit) {1,3} Between one and three (inclusive) of the previous expression (e.g., d{1,3} matches one, two or three digits) For more on regular expressions, see http://www.djangoproject.com/r/python/re-module/. 4.1.3 A Quick Note About 404 Errors At this point, our URLconf defines only a single URLpattern: the one that handles requests to the URL /hello/. What happens when you request a different URL? To find out, try running the Django development server and visiting a page such as http://127.0.0.1:8000/goodbye/ or http://127.0.0.1:8000/hello/subdirectory/, or even http://127.0.0.1:8000/ (the site “root”). You should see a “Page not found” message (see Figure
  • 7. regex  example   •  '^hello/’   /hello/foo   /hello/bar     •  ‘hello/$’   /foo/bar/hello/     •  ‘hello/‘   /foo/hello/bar     •  r'^Ame/plus/d+/$’   r'^Ame/plus/d{1,2}/$’      
  • 8. raw  string   r'n’  !=  ‘n’  
  • 9. Dynamic  URLs   •  Query  string  parameter  is  a  method.   •  But  Django’s  URLconf  system  encourages  preCy  URLs.   •  r'^Ame/plus/d+/$'   •  r'^Ame/plus/d{1,2}/$'   Python’s usage of backslashes and the backslashes that are found in regular expressions, so it’s s you use raw strings any time you’re defining a regular expression in Python. From now on, all this book will be raw strings. Now that we’ve designated a wildcard for the URL, we need a way of passing that wildcard dat so that we can use a single view function for any arbitrary hour offset. We do this by placing p data in the URLpattern that we want to save. In the case of our example, we want to save whatev in the URL, so let’s put parentheses around the d{1,2}, like this: (r’^time/plus/(d{1,2})/$’, hours_ahead), If you’re familiar with regular expressions, you’ll be right at home here; we’re using parenthese the matched text. The final URLconf, including our previous two views, looks like this: from django.conf.urls.defaults import * from mysite.views import hello, current_datetime, hours_ahead urlpatterns = patterns(’’, (r’^hello/$’, hello), (r’^time/$’, current_datetime), (r’^time/plus/(d{1,2})/$’, hours_ahead), ) With that taken care of, let’s write the hours_ahead view. Coding Order
  • 10. Dynamic  URLs   Django Book Documentation, Release 0.1 from django.http import Http404, HttpResponse import datetime def hours_ahead(request, offset): try: offset = int(offset) except ValueError: raise Http404() dt = datetime.datetime.now() + datetime.timedelta(hours=offset) html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt) return HttpResponse(html) Let’s step through this code one line at a time: • The view function, hours_ahead, takes two parameters: request and offset. – request is an HttpRequest object, just as in hello and current_datetime. We’ll say it again: each view always takes an HttpRequest object as its first parameter. – offset is the string captured by the parentheses in the URLpattern. For example, if the requested URL were /time/plus/3/, then offset would be the string ’3’. If the requested URL were /time/plus/21/, then offset would be the string ’21’. Note that captured values will always
  • 11. Debug  suggestion   •  assert  False   Below the “Request information” section, the “Settings” section lists all of the settings for this particular Django installation. (We’ve already mentioned ROOT_URLCONF, and we’ll show you various Django settings through- out the book. All the available settings are covered in detail in Appendix D.) The Django error page is capable of displaying more information in certain special cases, such as the case of template syntax errors. We’ll get to those later, when we discuss the Django template system. For now, uncomment the offset = int(offset) lines to get the view function working properly again. Are you the type of programmer who likes to debug with the help of carefully placed print statements? You can use the Django error page to do so – just without the print statements. At any point in your view, temporarily insert an assert False to trigger the error page. Then, you can view the local variables and state of the program. Here’s an example, using the hours_ahead view: def hours_ahead(request, offset): try: offset = int(offset) except ValueError: raise Http404() dt = datetime.datetime.now() + datetime.timedelta(hours=offset) assert False html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt) return HttpResponse(html) Finally, it’s obvious that much of this information is sensitive – it exposes the innards of your Python code and Django configuration – and it would be foolish to show this information on the public Internet. A malicious person could use it to attempt to reverse-engineer your Web application and do nasty things. For that reason, the Django error page is only displayed when your Django project is in debug mode. We’ll explain how to deactivate debug mode in Chapter 12. For now, just know that every Django project is in debug mode automatically when you start it. (Sound familiar? The “Page not found” errors, described earlier in this chapter, work the same way.) 4.7 What’s next? So far, we’ve been writing our view functions with HTML hard-coded directly in the Python code. We’ve done that to keep things simple while we demonstrated core concepts, but in the real world, this is nearly always a bad idea.