Python Django Tutorial 3 – views, simple urls and basic templates

A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything, really.

Create a simple view hello that will take the request from url HOSTNAME/hello and return a simple HTML page with a custom welcome message. Create the following view function in the file created by default in the Article app. You will have to import HttpResponse from django.http module in order to return the HtmlResponse from the view.

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def static_hello(request):
	name = 'Varun'
	html = "<html><body><h4>Hi %s,<br />This seems to have worked!</h4></body></html>" % name
	return HttpResponse(html)

2. URL
Now, we need to create a mapping so that Django can relate to the URL entered in the browser and pass on the processing to the hello view that we defined. We do this in the file created by default in the django_test project directory.

from article.views import hello
urlpatterns = [
    url(r'^admin/', include(,		#-- Added by default by Django
    url(r'^static-hello/', static_hello, name='static_hello')

Now navigate to and you’ll notice that the HTML response is showed on the page.

3. Template
A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted. Create a new directory called templates in the project home (where you have After creating this directory, modify the settings file so it can look for templates in this directory.

'DIRS': ['/Users/varun.verma/Work/scripts/python/setup/django-default/django_test/templates'],

The path for templates directory should be absolute and not relative.

Now let’s try to modify the view to render a response via a template. We’ll need a few imports to start with:

from django.template.loader import get_template

get_template is a helper function that helps get the template information from the settings file.

from django.template import Context

Context is important for Django template to understand how to render.

Create a new view in the file:

def dynamic_hello(request):
	name = 'Varun'
	template = get_template('dynamic_hello.html')    # Load the template
	html = template.render(Context({'name' : name})) # Render the template with our local Context
	return HttpResponse(html)                        # Send HTTP Response back

Create a new file dynamic_hello.html in the templates directory:


Hi {{ name }}, <br/>
This Dynamic Template seems to have worked.

Add a new URL to the file that can invoke the new dynamic_hello view:

from article.views import static_hello, dynamic_hello
urlpatterns = [
    url(r'^admin/', include(,
    url(r'^static-hello/', static_hello, name='static_hello'),
    url(r'^dynamic-hello/', dynamic_hello, name='dynamic_hello'),

Now navigate to and you’ll notice that the dynamic HTML response is showed on the page.

4. TemplateView / Class based views
Class-based views provide an alternative way to implement views as Python objects instead of functions. Django provides an example of some classes which can be used as views. These allow you to structure your views and reuse code by harnessing inheritance and mixins.

from django.views.generic.base import TemplateView
class HelloTemplate(TemplateView):
	template_name = 'hello_class.html'

	def get_context_data(self, **kwargs):
		context = super(HelloTemplate, self).get_context_data(**kwargs)
		context['name'] = 'Varun'
		return context

Create a new file hello_class.html under the templates directory defined in the settings file


Hi {{ name }}, <br/>
This Class Based view Template seems to have worked.

Add new URL,

from article.views import HelloTemplate
url(r'^classview-hello/', HelloTemplate.as_view(), name='classview_hello'),

5. render_to_response
Last but not the least – render_to_response. We saw earlier a 3 step approach to taking a request and returning a Http Response – load a template, render the template with the Context and return Http Response. render_to_response can do all of that by itself.

from django.shortcuts import render_to_response
def simple_dynamic_hello(request):
	name = 'Varun'
	return render_to_response('dynamic_hello.html', {'name' : name})

Add new URL:

from article.views import simple_dynamic_hello
url(r'^simpledynamic-hello/', simple_dynamic_hello, name='dynamic_hello'),

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s