Notes 10/15 on templates

settings.py

We have to specify the location of our templates folder. This is around line 105:

TEMPLATE_DIRS = (
    "/home/liucs/cs690/bookswap/templates"
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

urls.py

Notice the name= used for shortcut names with the {% url %} tag, and the parameter for the detail page, specified in parentheses. The \d means to match digits.

These lines are meant to be within the urlpatterns.

    url(r'^$', 'main.views.home', name='home'),
    url(r'^books/$', 'main.views.books', name='books'),
    url(r'^books/(\d+)$', 'main.views.detail', name='detail'),

views.py

# Create your views here.
from django.http import HttpResponse
from main.models import Book
from django.shortcuts import render_to_response

def home(request):
    # Collect information
    books = Book.objects.all()
    k = len(books)
    # Format text -- nah, do that in template
    #noun = "book" if k==1 else "books"
    #mesg = "We have " + str(k) + " " + noun
    return render_to_response("home.html",
        {'count': k})

def detail(request, id):
    book = Book.objects.get(id = id)
    return HttpResponse("Book detail view for " + book.title)

def books(request):
    books = Book.objects.all()
    return render_to_response("books.html",
        {'books': books})

templates/home.html

<html>
  <head>
    <title>Bookswap Home Page</title>
  </head>
  <body>
    <h1>Welcome to Bookswap!</h1>
    <p>This great service is coming soon.</p>
    <p>We have
        <a href="{% url books %}">
            {{count}} book{{count|pluralize}}
        </a>
        in stock.</p>
  </body>
</html>

templates/book.html

<html>
  <head>
    <title>Bookswap Book List</title>
  </head>
  <body>
    <h1>We have {{books|length}} book{{books|pluralize}}</h1>
    <ol>
        {% for b in books %}
            <li>
                <a href="{% url detail b.id %}">{{b.title}}</a>
                 with ISBN {{b.ISBN}}
            </li>
        {% endfor %}
    </ol>
  </body>
</html>