learning-website-django1-5 Exercise 2: Show a Real Page ====================================================== Replace the Chapter 2 placeholder views with real ones: find the page in the database by its path, check it belongs to this site, and render it inside the theme. Save as apps/content/views.py: from django.shortcuts import get_object_or_404, render from .models import Page def home(request, site): pages = Page.objects.light().filter(site=site) return render(request, "theme/home.html", {"page_count": pages.count(), "course_count": pages.exclude(course=None).values("course").distinct().count()}) def page(request, site, page_path): """An address such as /hungary/x/chapter/ is the file path hungary/x/chapter.html.""" path = page_path.rstrip("/") + ".html" page = get_object_or_404(Page, path=path, site=site) # a page of ANOTHER site is a 404 too # a page with its own

shows it; every other page gets one made from its title (as on the live site) show_h1 = "

body text

', html) def test_the_title_is_escaped_but_the_stored_body_is_not(self): self.make(title="x", fragment="y") html = self.get().content.decode() self.assertIn("<b>x</b>", html) self.assertIn("y", html) def test_a_page_without_its_own_h1_gets_one_made_from_its_title(self): self.make() self.assertIn('

Buying Clothes: Sizes & Fit

', self.get().content.decode()) def test_a_page_with_its_own_h1_does_not_get_a_second(self): self.make(fragment="

Its own

x

") self.assertEqual(self.get().content.decode().lower().count("x shows as text). - A page without its own h1 gets one made from its title; a page with one does not get a second. - A missing page, and a page whose stored site disagrees with the address, are 404s. WHY THIS WORKS AS AN ANSWER --------------------------- The view is six lines, and the tests pin down everything that could go wrong around it: the site boundary, the escaping rules, the heading rule, the load order and the readability of every colour.