At the Forge - Django Views and Templates
Last month, we began looking at Django, a popular framework for creating Web applications in Python. Django has the reputation of being the “Ruby on Rails of the Python world”, and there is some justification for that description. Even though Django was developed in parallel with Rails and has many unique features that distinguish it from its Ruby counterpart, it's difficult to avoid comparing the two.
In the introduction to Django last month, we saw a number of subtle, but important, differences between the two systems. Django handles a “project” at a time, where each project may contain one or more applications. This contrasts with the Rails approach, in which there is no real equivalent to Django's projects, because everything is an application.
We also saw that Django comes with a built-in Web-based administrative system. It takes a tiny bit of fiddling with a configuration file to activate this administrative system, but it provides a great number of benefits to any system that uses it.
Despite their differences, both Django and Rails use an approach that is best known as MVC (model, view, controller) developed in the Smalltalk community but adopted by many other languages and frameworks since then. These terms, used verbatim in the Rails world, are called models, templates and views in the Django world, and they form the bulk of a Django-based site.
This month, we work with templates and views, ignoring models and the database API until next month. But, don't worry; Django's templates are quite powerful, and they provide an interesting lesson in restraint.
Our first step involves creating a new application within our project. For a number of reasons, including the simplicity with which we can create a page, our example application is a very simple blog program. We create our blog application by switching into our project directory, and then by using our management program, manage.py:
$ cd /opt/atf/mysite $ python manage.py startapp blog
If this executes successfully, Django won't print any messages. Rather, we can get a listing of the current directory, which should now include a blog subdirectory:
$ ls blog __init__.py models.py views.py
Django is smart enough to stop us from creating an application twice, if we try to do so:
$ python manage.py startapp blog Error: [Errno 17] File exists: '/opt/atf/mysite/blog'
Now, let's create a simple “Hello, world” view, just so we can demonstrate that things are working. Thus, we open blog/views.py, which starts off empty except for a comment indicating that this is the file in which views are defined.
The simplest possible “Hello, world” view will be called index, acting sort of like the index method in Rails or the index.html file on a Web site—providing the default content when no specific method is invoked for an application. We also have to import the Python module in which Django's HTTP response capabilities are defined. When we're done, the entire views.py file looks like this:
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world.")
If our server isn't already running, we can start it with:
python manage.py runserver
Or, if we want to run on a publicly accessible IP address, rather than 127.0.0.1 (“localhost”), we can do something like this:
python manage.py runserver 69.55.232.87:8000
To see the output from our view, let's point our browser to the following URL, expecting to see “Hello, world”: http://69.55.232.87:8000/blog/. Instead, we get an error message, indicating that Django has no idea what we're talking about. The good news is that this error message, which is turned on only when we are developing an application, tells us what we did wrong—namely, that our URLConf definition failed to have any entry for blog in it.
This is a fundamental difference between Django and Rails, and it reflects the different philosophies of the two communities. In Rails, you expect the system to do the right thing by default; you should have to say something only when it deviates from that norm. In contrast, Django assumes that you want to make everything explicit.
Among the things that you need to make explicit is the way in which URLs are translated into method calls. The Django system for doing this is called URLConf, and it is a set of regular expressions defined for the entire project. (It functions something like routes in Rails.) If you are familiar with regular expressions, it should be pretty easy to add or modify URLConf.
For example, let's say we want the /blog/ URL to go to our blog application. So, we would open the URLConf file, which for the mysite project will be in mysite/urls.py. (We already modified this last month, when we added administrative capabilities to our Django site.) We then add a line that looks like the following:
(r'^blog/$', 'mysite.blog.views.index')
In other words, if the system sees a URL that begins with blog and ends with /, it should invoke the index method within views.py in our blog application. And, sure enough, as soon as we save urls.py to disk, we can reload our URL http://69.55.232.87:8000/blog/, and in our browser, we see “Hello, world”. Our Django application is starting to come together.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.
Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.
Sponsored by ActiveState
| Speed Up Your Web Site with Varnish | Jun 19, 2013 |
| Non-Linux FOSS: libnotify, OS X Style | Jun 18, 2013 |
| Containers—Not Virtual Machines—Are the Future Cloud | Jun 17, 2013 |
| Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer | Jun 12, 2013 |
| Weechat, Irssi's Little Brother | Jun 11, 2013 |
| One Tail Just Isn't Enough | Jun 07, 2013 |
- Containers—Not Virtual Machines—Are the Future Cloud
- Non-Linux FOSS: libnotify, OS X Style
- Linux Systems Administrator
- Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer
- Validate an E-Mail Address with PHP, the Right Way
- Technical Support Rep
- Senior Perl Developer
- UX Designer
- Web & UI Developer (JavaScript & j Query)
- Introduction to MapReduce with Hadoop on Linux
- Cari Uang
2 hours 8 min ago - user namespaces
5 hours 1 min ago - yea
5 hours 27 min ago - One advantage with VMs
7 hours 56 min ago - about info
8 hours 29 min ago - info
8 hours 30 min ago - info
8 hours 31 min ago - info
8 hours 33 min ago - info
8 hours 34 min ago - abut info
8 hours 35 min ago
Featured Jobs
| Linux Systems Administrator | Houston and Austin, Texas | Host Gator |
| Senior Perl Developer | Austin, Texas | Host Gator |
| Technical Support Rep | Houston and Austin, Texas | Host Gator |
| UX Designer | Austin, Texas | Host Gator |
| Web & UI Developer (JavaScript & j Query) | Austin, Texas | Host Gator |
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




Comments
Thanks!
Good article. I am newbie to framework web development. I found django to be very picky. And this article helped me get started.
Suggestion for other newbies: Follow the article strictly for the first time. After you are successful in the first pass, make changes to suit your own needs.
Minor Syntax Point
Great article, I like your approach, I'm a fan of your column and LJ in general.
One thing that you might want to fix is the function definitions for the views. The Python code should be indented properly otherwise it won't run. Maybe my browser or the rendering was off, but you might want to check it, or just mention it.
Thanks for taking a tour of Django and writing about it. I've been using Django for a little while now and enjoy working with it very much.