Python Django Tutorial 4(b) – Advanced views and urls

1. Defining URL’s within the App
So far, we had defined all URL’s in the main project’s file. But the purpose of having an app is that it can be a standalone module that can be plugged into any other project. For the same reason, it is nice to define all the URL’s related to the app contained with the app.

Create a new within the articles app. This is explained as per Django version 1.8. URL imports works in a different fashion for older Django versions.

from django.conf.urls import patterns, include, url
from article.views import articles, article

urlpatterns = [
	url(r'^all/$', articles, name='articles'),
	url(r'^get/(?P<article_id>\d+)/$', article, name='article'),

The part of code (?P<article_id>\d+) denotes a variable/parameter (?P) is named article_id will be of type digit of any length greater than 1 (\d+).

Now modify the within the project folder so that it is able to include the file that is created under the articles app.

urlpatterns = [
    url(r'^articles/', include('article.urls')),

The above denotes that anything starting with articles will look for the next segment of the URL within the article.urls file.

2. Creating views
Let’s define 2 more views in the file under articles. The first one would take the article_id parameter from the URL and use it to show the article header and body, e.g. view for this URL

def article(request, article_id = 1):
	return render_to_response('article.html', {'article' : Article.objects.get(id=article_id)})

This view takes in a new parameter article_id apart form the standard request parameter. If you look back, the name of the parameter is defined within the URL (?P

\d+). The view calls the magical render_to_response by passing in the article object corresponding to the article_id.

The other view would list all the articles in the database, e.g. view for this url

def articles(request):
	return render_to_response('articles.html', {'articles' : Article.objects.all()})

This view passes all article objects to the template articles.html

3. Creating templates
The first template (article.html) takes in a single article object and displays it’s title and body.

<h1>{{ article.title }}</h1>
<p>{{ article.body }}</p>

The second template (articles.html) lists all the articles in the database with a link to access their individual article page.

{% for article in articles %}
<h2><a href="/articles/get/{{ }}/">{{ article.title }}</a></h2>
<p>{{ article.body }}</p>
{% endfor %}

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 )

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