0% found this document useful (0 votes)
109 views19 pages

Django Views and URLconfs

The document discusses Django views and URL configurations (URLconfs). It explains that views are Python functions that take a request and return a response, while URLconfs map URLs to their corresponding views. Views can be used to dynamically generate content by accessing variables like the current date/time. URLconfs allow loosely coupling URLs and views through patterns that pass wildcard data to views. This allows a single view to handle multiple URLs by accessing the wildcard values.

Uploaded by

Abhinav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views19 pages

Django Views and URLconfs

The document discusses Django views and URL configurations (URLconfs). It explains that views are Python functions that take a request and return a response, while URLconfs map URLs to their corresponding views. Views can be used to dynamically generate content by accessing variables like the current date/time. URLconfs allow loosely coupling URLs and views through patterns that pass wildcard data to views. This allows a single view to handle multiple URLs by accessing the wildcard values.

Uploaded by

Abhinav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Django Views and URLconfs

By
Dr. Amrita Chaturvedi
Django – Powered Page
 To create a web page without a web
framework:
◦ Create a web page hello.html and upload it to
a directory on a web server somewhere.
◦ For a web page: you specify the contents and
the URL.
 With Django:
◦ Contents of the page are produced by a view
function
◦ URL is specified in a URLconf
First View
 In the inner mysite directory:
◦ create an empty file called views.py
◦ Views.py:
 from django.http import HttpResponse
 def hello(request):
 return HttpResponse("Hello world")
◦ Request is an instance of the class
django.http.HttpRequest
◦ A view is just a Python function that takes an
HttpRequest as its first parameter and returns an
instance of HttpResponse. In order for a Python
function to be a Django view, it must do these
two things.
First URLconf
 A URLconf is like a table of contents for
your Django-powered web site.
 Basically, it’s a mapping between URLs and
the view functions that should be called for
those URLs.
 When you execute django-admin
startproject, the script creates a URLconf for
you automatically: the file urls.py.
◦ from django.conf.urls import url
◦ from django.contrib import admin
◦ urlpatterns = [ url(https://www.scribd.com/r'^admin/',%20admin.site.urls), ]
First URLconf
 urlpatterns defines the mapping between URLs
and the code that handles those URLs.
 To add a URL and view to the URLconf, just add a
mapping between a URL pattern and the view
function.
◦ from django.conf.urls import url
◦ from django.contrib import admin
◦ from mysite.views import hello
◦ urlpatterns = [ url(https://www.scribd.com/r'^admin/',%20admin.site.urls),
url(https://www.scribd.com/r'^hello/r'^hello/$', hello#39;,%20hello), ]
 The last line tells Django that any request to the
URL /hello/ should be handled by the hello view
function.
First URLconf
 URLpattern doesn’t include the leading slash in
/hello/.
 ‘^’ means require that the pattern matches the
start of the string.
 ‘$’ means require that the pattern matches the
end of the string.
 Example:
◦ ^hello/ - any URL starting with /hello/ would match,
such as /hello/foo and /hello/bar
◦ hello/$ - any URL that ends with hello/ would match,
such as /foo/bar/hello/
◦ hello/ - any URL containing hello/ would match, such
as /foo/hello/bar
First URLconf
 APPEND_SLASH Django setting: /hello
doesn’t match. By default, any request to a
URL that doesn’t match a URLpattern and
doesn’t end with a slash will be redirected
to the same URL with a trailing slash
 You can pass hello view function as an
object without calling the function.
 In python, functions are first-class objects.
Regular Expressions
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)
Between one and three (inclusive) of the previous expression
{1,3}
(e.g., \d{1,3} matches one, two or three digits)
Errors
 404 error: occurs when you request an
undefined URL like
http://127.0.0.1:8000/goodbye/
 You get a page not found message
 Site root: to implement a view for the site
root, use the URLpattern “^$“, which
matches an empty string.
 Example:
◦ from mysite.views import hello,
my_homepage_view
◦ urlpatterns = [ url(https://www.scribd.com/r'^r'^$', my_homepage_view#39;,%20my_homepage_view),
◦ # ...
How Django processes a request
 When you run python manage.py runserver, the script looks
for a file called settings.py in the inner mysite directory.
 The auto-generated settings.py contains a
ROOT_URLCONF setting that points to the auto-generated
urls.py.
 ROOT_URLCONF = 'mysite.urls‘
 When a request comes in for a particular URL – Django
loads the URLconf pointed to by the ROOT_URLCONF
setting.
 Then it checks each of the URLpatterns in that URLconf,
until it finds one that matches.
 When it finds one that matches, it calls the view function
associated with that pattern, passing it an HttpRequest
object as the first parameter.
 a view function must return an HttpResponse.
How Django processes a request
 A request comes in to /hello/.
 Django determines the root URLconf by looking
at the ROOT_URLCONF setting.
 Django looks at all of the URLpatterns in the
URLconf for the first one that matches /hello/.
 If it finds a match, it calls the associated view
function.
 The view function returns an HttpResponse.
 Django converts the HttpResponse to the proper
HTTP response, which results in a web page.
Dynamic Web Page
 Create a web page that displays current date time.
from django.http import HttpResponse
import datetime
def hello(request):
return HttpResponse("Hello world")
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
 The now variable is technically a datetime.datetime object,
not a string, but the %s format character converts it to its
string representation, which is something like “2017-09-08
14:32:25.412665“.
 This will result in an HTML string such as “It is now 2017-09-
08 14:32:25.412665.“.
Dynamic Web Page
 Add the URLpattern to urls.py:
from django.conf.urls import url
from django.contrib import admin
from mysite.views import hello,
current_datetime urlpatterns = [
url(https://www.scribd.com/r'^admin/',%20admin.site.urls),
url(https://www.scribd.com/r'^hello/r'^hello/$', hello#39;,%20hello),
url(https://www.scribd.com/r'^time/r'^time/$', current_datetime#39;,%20current_datetime), ]
 To see the current date and time, you
should visit http://127.0.0.1:8000/time/
URLconfs and Loose Coupling
 loose coupling is a software-development
approach that values the importance of
making pieces interchangeable.
 If two pieces of code are loosely coupled,
then changes made to one of the pieces
will have little or no effect on the other.
 In a Django web application, the URL
definitions and the view functions they
call are loosely coupled
URLconfs and Loose Coupling
 Example: to make current_datetime
available at two URLs.
urlpatterns = [ url(https://www.scribd.com/r'^admin/',%20admin.site.urls),
url(https://www.scribd.com/r'^hello/r'^hello/$', hello#39;,%20hello),
url(https://www.scribd.com/r'^time/r'^time/$', current_datetime#39;,%20current_datetime),
url(https://www.scribd.com/r'^another-time-page/r'^another-time-page/$',
current_datetime#39;,%3Cbr/%20%3E%20%20%20%20%20current_datetime), ]
Dynamic URLs
 Create a view that displays the current date
and time offset by a certain number of
hours.
 A novice might think to code a separate
view function for each hour offset, which
might result in a URLconf like this:
urlpatterns = [ url(https://www.scribd.com/r'^time/r'^time/$', current_datetime#39;,%20current_datetime),
url(https://www.scribd.com/r'^time/plus/1/r'^time/plus/1/$', one_hour_ahead#39;,%20one_hour_ahead),
url(https://www.scribd.com/r'^time/plus/2/r'^time/plus/2/$', two_hours_ahead#39;,%20two_hours_ahead),
url(https://www.scribd.com/r'^time/plus/3/r'^time/plus/3/$', three_hours_ahead#39;,%20three_hours_ahead), ]
Dynamic URLs
 The key is to use wildcard URLpatterns.
 We can use the regular expression pattern
\d+ to match one or more digits:
◦ urlpatterns = [ # ... url(https://www.scribd.com/r'^time/plus/\d+/r'^time/plus/\d+/$',
hours_ahead#39;,%3Cbr/%20%3E%20%20%20%20%20%20hours_ahead), # ... ]
◦ This new URLpattern will match any URL such as
/time/plus/2/, /time/plus/25/, or even
/time/plus/100000000000/.
 we can set a maximum 99 hours by only
allowing either one- or two-digit numbers
◦ url(https://www.scribd.com/r'^time/plus/\d{1,2}/r'^time/plus/\d{1,2}/$', hours_ahead#39;,%20hours_ahead),
Dynamic URLs
 we need a way of passing the wildcard data
to the view function, so that we can use a
single view function for any arbitrary hour
offset.
 We do this by placing parentheses around
the data in the URLpattern that we want to
save.
 In the case of our example, we want to save
the number that was entered in the URL, so
we put parentheses around the \d{1,2},
◦ url(https://www.scribd.com/r'^time/plus/(\d{1,2})/$', hours_ahead),
Dynamic URLs
 The hours_ahead view:
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)
Try http://127.0.0.1:8000/time/plus/5/
 Output of http://127.0.0.1:8000/time/plus/100/ and
http://127.0.0.1:8000/time/plus/ ?

You might also like