Django Tutorial - Video 3 - Views and Templates

This tutorial walks through an introduction to the View layer and the urls.py file that evaluates the calling URL with a regular expression engine and passes the request to the specified view. We also look at building response objects and using the templating system to display the results from a view. Finally, we look at using the django interactive shell to build/test our views.


beer/views.py

from django.shortcuts import render_to_response
from django.template import RequestContext
from beer.models import Beer, Brewery

def BeersAll(request):
        beers = Beer.objects.all().order_by('name')
        context = {'beers': beers}
        return render_to_response('beersall.html', context, context_instance=RequestContext(request))

def SpecificBeer(request, beerslug):
        beer = Beer.objects.get(slug=beerslug)
        context = {'beer': beer}
        return render_to_response('singlebeer.html', context, context_instance=RequestContext(request))

def SpecificBrewery(reqeust, breweryslug):
        brewery = Brewery.objects.get(slug=breweryslug)
        beers = Beer.objects.filter(brewery=brewery)
        context = {'beers': beers}
        return render_to_response('singlebrewery.html', context, context_instance=RequestContext(reqeust))
		

templates/beersall.html

{% extends "base.html" %}
{% block content %}
        <div id="beerslist">
                {% for beer in beers %}
                <p><a href="/beers/{{ beer.slug }}/"><img src="{{ beer.image1.url }}" />{{ beer }}</a></p>
                {% endfor %}
        </div>
{% endblock %}
		

templates/singlebeer.html

{% extends "base.html" %}
{% block content %}
        <div id="singlebeer">
                <p>Name: {{ beer }}</p>
                <p>Locality: {{ beer.get_locality_display }}</p>
                <p>Brewery: <a href="/brewerys/{{ beer.brewery.slug }}/">{{ beer.brewery }}</a></p>
        </div>
{% endblock %}
		

templates/singlebrewery.html

{% extends "base.html" %}
{% block content %}
        <div id="beerslist">
                <h2>Beers from {{ beers.0.brewery }}</h2>
                {% for beer in beers %}
                <p><a href="/beers/{{ beer.slug }}/">{{ beer }}</a></p>
                {% endfor %}
        </div>
{% endblock %}
		

urls.py

from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.views.generic.simple import direct_to_template
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    (r'^$', 'pages.views.MainHomePage'),
    (r'^beers/$', 'beer.views.BeersAll'),
    (r'^beers/(?P<beerslug>.*)/$', 'beer.views.SpecificBeer'),
    (r'^brewerys/(?P<breweryslug>.*)/$', 'beer.views.SpecificBrewery'),
)