Django: Getting Started Transcripts
Chapter: Introducing the Django Web Framework
Lecture: Mapping URLs to code
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
So you've seen how the entry point to Django is the URL mapping. What exactly is this? It's a Python list that contains references to routes.
0:11
There are several different ways of expressing a URL match. Ranging from simple text to more complicated regular expressions.
0:18
Each route you specify can map to a view function that returns an HTTPResponse object or if you'd rather something more object oriented,
0:27
there is a way of building views with classes as well. Although personally I prefer the functions and you can also map to another mapping.
0:36
This works well if you've got a self contained module you can nest all that module's URLs under a root URL
0:44
If you like hierarchical organization for the win. URLs map to views. A view is where your business logic goes and is responsible
0:54
for returning some content. That content is expressed as an HTTPResponse object. There are other kinds of objects as well,
1:02
but this course will only use this one. A view can take arguments. Django prefers to place arguments inside the URL rather than using query parameters.
1:13
It supports the latter, but the former maps nicely like I mentioned before. I tend to name my views the same thing as my URL So the joint group URL
1:22
That needs two parameters specifies them as part of the URL itself and Django will map that to the arguments in your
1:30
joint group view. You'll notice that these arguments are the 2nd and 3rd to the
1:35
view. All views take a request object that gives information about the http request as the first argument. Views can be either functions or classes.
1:46
The function style tends to be a bit more verbose but also tends to be a bit easier to read. It explicitly tells you what is happening.
1:54
The class style wraps something so that you don't have to write as much code, but you have to remember what magic things the class does for you.
2:03
Typically each view is going to spit out some HTML. It does this by using the template engine to create some content.
2:09
This is so common there is a library full of shortcuts that encapsulates this process
2:14
in Django and of course you might not need to write your own view either. Django ships with some. That may mean you have less code to write.
2:23
One example covered in a future chapter is to do a redirect. This can be done in a single line because Django provides you a pre canned view
2:31
for exactly this purpose.