Skip to content

How to add a page

Théophile MADET edited this page Jun 27, 2024 · 5 revisions

In this example

  • Defining URLs
  • Working with views
  • Dynamic content with context data

External documentation

Our simplest example : the About page

Before you can render even a very simple page, there are several steps you need to go through. In this example, we'll look at the About page and all the parts that are needed for it to be accessible. This is the simplest example because it is just a static page : it doesn't contain any logic and just renders a static HTML page.

Getting started - the minimum code you need to render a page

The view class

In Django, pages are called Views. The first step is create a class1 that inherits from View:

class AboutView(TemplateView):
    template_name = "coop/about.html"

Views are defined under tapir/[YOUR_APP]/views, where views is either a file or a package.

There are many different kinds of view. Most of them have a template, but since our example only has a template it's called TemplateView.

The template

Template files are under tapir/[YOUR_APP]/templates/[YOUR_APP]/[YOUR_TEMPLATE].html2.

While template files use the .html extension, they are actually a bit more than just HTML. The full documentation is here, but it's basically normal HTML with {% %} blocks on top. Those {% %} can access and format data sent by the view class. For example in our coop/about.html example, there is a title set as {% translate "Latest changes" %}.

The URL

We now have our simple view that can render our simple template. Next we need to link that view to an URL. This is done in tapir/[YOUR_APP]/urls.py and looks like this:

urlpatterns = [
    ...
    path(
        "about",
        views.AboutView.as_view(),
        name="about",
    ),
    ...
]

You can then access the page under localhost:8000/[YOUR_APP]/about.

And that's it! With those 3 elements (view class, template, url), you have the minimum steps to create a new page.

Dynamic templates with context data

Our about page example is static: the content of the page is always the same. Most interesting pages need to display dynamic values depending on the state of the app. This is done with the get_context_data method, that you can define on most class based views. For example, if we wanted to add the number of members to our About page, we would add the following method to our AboutView page:

def get_context_data(self, **kwargs):
    context = super().get_context_data()
    context["number_of_members"] = ShareOwner.objects.count()
    return context

Then, in our about.html, we can add:

<div>The number of members is: {% number_of_members %}</div>

[1]: There are also "function based views", but in Tapir we almost always use "class based views"

[2]: That's [YOUR_APP] twice, it's the recommended way to organize the folder structure. See "Template namespacing" under this paragraphe