Day 4 - Advanced Views and URLs

Catching up on a few posts…. I’ve been making progress, but failing to post about them, so here goes:

On Day 4, which was roughly 5 days ago, I took Lecture 5 of the Learn Python Django from scratch course. Basically, this lecture was about using the ‘Django app directory’ to store the views that map to the HTML used to display the app content. Take a look at the code:

from article.models import Article

# Create your views here.
''' def hello(request):
    name = "Jay"
    html = "<html><body>Hi %s. It worked.</body></html>" % name
    return HttpResponse(html)

def hello_template(request):
    name = "Jay"
    t = get_template('hello.html')
    html = t.render(Context({'name': name}))
    return HttpResponse(html) '''

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

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

We defined a few new methods to handle a couple different cases. The first method takes care of the case where a request is made to the website for ALL of the articles in the web app. The second method takes a parameter, the article id, and it returns the article requested to the articles view for display purposes.

Where do we define these request cases? In the file: :

from django.conf.urls import patterns, include, url

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

You can see the regular expression that represents the /all/ URL, which passes the request on to the articles (plural) method. The other regular expression /get/ some_number /, will pass the number in the URL as the id parameter in the article (singular) method.

Finally, we had to create the views template to handle both requests. Have a look:

articles.html :



Quite simple, here. For all the articles returned in either method call, the for loop in the HTML will display 1 or all of the articles data requested.

That’s it. Onto blogging the next day…

Jason T Clark

Jason T Clark

Father. Musician. Gamer. Coder.

comments powered by Disqus
rss facebook twitter github youtube mail spotify instagram linkedin