This mini tutorial explains how to serve a simple web page through Django that display’s a traditional ‘Hello world’ message.
In Django, the contents of the page are produced by view a function, which you place in a file you create, conventionally named views.py. The URL of the page itself is specified in a URLconf,, which you specify in urls.py.
To output a simple Hello world! message, add this to your new views.py:
from django.http import HttpResponsedef hello(request): return HttpResponse("Hello world")
- Import the HttpResponse class, from django/http/ (or, the django.http module)
- Define a function called
hello. This is our view function.
- Return an HttpResponse object that’s been instantiated with the text
In order for a Python function to be a Django view, it must do two things:
- Takes an HttpRequest as its first parameter.
- Return an instance of HttpResponse.
Each view function takes at least one parameter, called
request by convention.
If we ignore the code that’s commented out of the urls.py file (the one that was created when you first created your Django testProject folder), we’re left simply with:
from django.conf.urls.defaults import *urlpatterns = patterns('',)
- Import all objects from the django/conf/urls/defaults/ (the django.conf.urls.defaults module). This includes the proceeding function,
- Calls the function
patternsand save the result into a variable called
Edit the URLconf:
from django.conf.urls.defaults import *from mysite.views import hellourlpatterns = patterns('', ('^hello/$', hello),)
- Import the
helloview from the
- Any request to the URL
/hello/should be handled by the hello view function.
Things to remember
mysite/views.pymust be on your Python path.
- If you want to load this page from Apache as http://127.0.0.1/hello instead of as http://127.0.0.1:8000/hello from Django’s development server, make sure that the following is in Apache’s configuration file (httpd.conf):
Allow from all </Directory>
- The URLpattern
('^hello/$', hello),is a Python tuple in which the first element is a regular expression, and the second is the view function to use for that pattern.
Test your first Django page
Either run the command
python manage.py runserver to view your
/hello/ page in Django’s development server at http://127.0.0.1:8000/hello, or view it with your Apache web server at http://127.0.0.1/hello .
The page you see from this example is static; the content doesn’t change from user input, nor does it involve any database. Move on to a simple example of a dynamic Django page—as well as to an introduction to dynamic URLs—in Chapter 3 of DjangoBook: Views and URLconfs.