Skip navigation

In the previous entry I explained how to create a new project, app and how to add an app to the project. In this entry, I’ll show how to implement a MVC in Django.

Recall that our project directory tree looks as follows:

<project_name>/

<app_name>/
__init__.py
models.py
views.py

__init__.py
manage.py
settings.py
urls.py

The first thing we need to do is to tell Django which methods will handle requests. This is done in the urls.py by adding a tuple of tuples with a name urlpatterns. The tuples are of the form:

(regular expression, Python callback function [, optional dictionary])

The first item is a regular expression that matches URL we want to handle. The second item is the full path to the function to handle the request. The dictionary is keyword arguments. The methods to handle the request must be inside the views.py file.

Inside the handler methods we can do anything that Python allows us to do. One condition is that the method must return an object of type HttpResponse. The next step is to create templates to handle the presentation. First thing we must do is decide where to put templates. The path to templates is added to TEMPLATE_DIRS tuple in settings.py. After we’ve added this template, we must tie it with the method that handles the request. This is done by creating a django.template.Context object, which is just a mapping of Python objects inside the method and their respective names inside the template. Then, we must load the actual template by calling django.template.loader.get_template(<template_name>). Finally, we render the template by calling render on the loader and passing to it the Context object, and return the resulting HttpResponse object.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: