banner



How To Add All Values In A Column In Django Template Tags

Django Tutorial Part half-dozen: Generic list and detail views

  • Previous
  • Overview: Django
  • Next

This tutorial extends our LocalLibrary website, adding list and detail pages for books and authors. Here we'll larn about generic class-based views, and testify how they tin can reduce the amount of code yous have to write for common use cases. We'll also go into URL treatment in greater detail, showing how to perform basic pattern matching.

Overview

In this tutorial we're going to complete the first version of the LocalLibrary website past adding list and detail pages for books and authors (or to exist more precise, we'll prove y'all how to implement the book pages, and get you lot to create the author pages yourself!)

The process is similar to creating the index page, which nosotros showed in the previous tutorial. Nosotros'll nonetheless demand to create URL maps, views, and templates. The main deviation is that for the detail pages, we'll have the additional claiming of extracting information from patterns in the URL and passing information technology to the view. For these pages, we're going to demonstrate a completely dissimilar blazon of view: generic course-based list and detail views. These can significantly reduce the amount of view code needed, making them easier to write and maintain.

The final part of the tutorial will demonstrate how to paginate your information when using generic class-based list views.

Book list folio

The book list page will display a list of all the available book records in the page, accessed using the URL: itemize/books/. The folio volition display a title and writer for each tape, with the title being a hyperlink to the associated volume detail page. The page will have the same construction and navigation as all other pages in the site, and we can, therefore, extend the base of operations template (base_generic.html) we created in the previous tutorial.

URL mapping

Open up /catalog/urls.py and copy in the line setting the path for 'books/', as shown beneath. Simply as for the index page, this path() office defines a design to match against the URL ('books/'), a view function that volition exist called if the URL matches (views.BookListView.as_view()), and a proper name for this particular mapping.

                urlpatterns                  =                  [                  path(                  ''                  ,                  views.index,                  name=                  'index'                  )                  ,                  path(                  'books/'                  ,                  views.BookListView.as_view(                  )                  ,                  name=                  'books'                  )                  ,                  ]                              

As discussed in the previous tutorial the URL must already have matched /catalog, so the view will really exist chosen for the URL: /catalog/books/.

The view function has a dissimilar format than before — that'due south because this view will actually be implemented as a course. Nosotros will be inheriting from an existing generic view function that already does most of what nosotros want this view function to do, rather than writing our own from scratch.

For Django grade-based views we access an appropriate view function by calling the class method as_view(). This does all the piece of work of creating an instance of the class, and making certain that the right handler methods are called for incoming HTTP requests.

View (class-based)

Nosotros could quite easily write the book listing view equally a regular function (simply like our previous index view), which would query the database for all books, and then telephone call return() to pass the list to a specified template. Instead, however, we're going to utilize a class-based generic list view (ListView) — a class that inherits from an existing view. Because the generic view already implements most of the functionality nosotros need and follows Django best-exercise, we will exist able to create a more robust listing view with less code, less repetition, and ultimately less maintenance.

Open catalog/views.py, and re-create the following code into the bottom of the file:

                                  from                  django.views                  import                  generic                  class                  BookListView                  (generic.ListView)                  :                  model                  =                  Volume                              

That'due south it! The generic view will query the database to get all records for the specified model (Book) then render a template located at /locallibrary/itemize/templates/catalog/book_list.html (which nosotros will create below). Within the template y'all can admission the list of books with the template variable named object_list OR book_list (i.e. generically "the_model_name_list").

Note: This bad-mannered path for the template location isn't a misprint — the generic views look for templates in /application_name/the_model_name_list.html (itemize/book_list.html in this instance) inside the application'south /application_name/templates/ directory (/itemize/templates/).

Yous tin add attributes to change the default behavior in a higher place. For example, you can specify another template file if you need to have multiple views that apply this same model, or you might desire to apply a different template variable name if book_list is non intuitive for your particular template use-case. Mayhap the most useful variation is to change/filter the subset of results that are returned — so instead of listing all books you might list meridian 5 books that were read by other users.

                                  course                  BookListView                  (generic.ListView)                  :                  model                  =                  Book     context_object_name                  =                  'my_book_list'                  # your ain proper noun for the list as a template variable                  queryset                  =                  Book.objects.                  filter                  (title__icontains=                  'war'                  )                  [                  :                  5                  ]                  # Get v books containing the title war                  template_name                  =                  'books/my_arbitrary_template_name_list.html'                  # Specify your own template name/location                              

Overriding methods in form-based views

While we don't need to do so here, you tin can besides override some of the class methods.

For instance, we can override the get_queryset() method to alter the listing of records returned. This is more flexible than simply setting the queryset aspect as we did in the preceding code fragment (though there is no existent benefit in this case):

                                  form                  BookListView                  (generic.ListView)                  :                  model                  =                  Book                  def                  get_queryset                  (self)                  :                  return                  Volume.objects.                  filter                  (title__icontains=                  'war'                  )                  [                  :                  five                  ]                  # Get v books containing the title war                              

We might also override get_context_data() in order to pass additional context variables to the template (e.yard. the list of books is passed by default). The fragment below shows how to add together a variable named "some_data" to the context (it would and so be available as a template variable).

                                  class                  BookListView                  (generic.ListView)                  :                  model                  =                  Book                  def                  get_context_data                  (cocky,                  **kwargs)                  :                  # Call the base implementation first to become the context                  context                  =                  super                  (BookListView,                  self)                  .get_context_data(                  **kwargs)                  # Create any information and add information technology to the context                  context[                  'some_data'                  ]                  =                  'This is but some information'                  return                  context                              

When doing this it is important to follow the pattern used above:

  • Commencement get the existing context from our superclass.
  • Then add your new context information.
  • Then return the new (updated) context.

Creating the List View template

Create the HTML file /locallibrary/catalog/templates/catalog/book_list.html and re-create in the text below. Every bit discussed above, this is the default template file expected by the generic class-based listing view (for a model named Book in an application named catalog).

Templates for generic views are just like any other templates (although of class the context/data passed to the template may differ). As with our alphabetize template, we extend our base template in the commencement line and and so replace the block named content.

                {% extends "base_generic.html" %}  {% block content %}                                                            <h1                    >                  Book List                                          </h1                    >                                    {% if book_list %}                                                            <ul                    >                                    {% for volume in book_list %}                                                            <li                    >                                                                              <a                    href                                          =                      "{{ book.get_absolute_url }}"                                        >                  {{ book.title }}                                          </a                    >                                    ({{book.writer}})                                                            </li                    >                                    {% endfor %}                                                            </ul                    >                                    {% else %}                                                            <p                    >                  There are no books in the library.                                          </p                    >                                    {% endif %} {% endblock %}                              

The view passes the context (listing of books) past default every bit object_list and book_list aliases; either will work.

Conditional execution

We use the if, else, and endif template tags to cheque whether the book_list has been defined and is not empty. If book_list is empty, then the else clause displays text explaining that there are no books to list. If book_list is non empty, and then we iterate through the list of books.

                {% if book_list %}                  <!-- code here to list the books -->                  {% else %}                                                            <p                    >                  There are no books in the library.                                          </p                    >                                    {% endif %}                              

The condition above only checks for one case, but yous tin test on additional conditions using the elif template tag (e.g. {% elif var2 %}). For more than information about conditional operators see: if, ifequal/ifnotequal, and ifchanged in Built-in template tags and filters (Django Docs).

For loops

The template uses the for and endfor template tags to loop through the book list, as shown beneath. Each iteration populates the book template variable with data for the electric current listing item.

                {% for book in book_list %}                                                            <li                    >                                    <!-- code here get information from each book item -->                                                            </li                    >                                    {% endfor %}                              

Yous might as well use the {% empty %} template tag to ascertain what happens if the volume list is empty (although our template chooses to apply a conditional instead):

                                                                            <ul                    >                                    {% for book in book_list %}                                                            <li                    >                                    <!-- code here go information from each book item -->                                                            </li                    >                                    {% empty %}                                                            <p                    >                  There are no books in the library.                                          </p                    >                                    {% endfor %}                                                            </ul                    >                                                

While not used here, within the loop Django will as well create other variables that yous can utilize to track the iteration. For example, y'all can examination the forloop.last variable to perform conditional processing the last fourth dimension that the loop is run.

Accessing variables

The code inside the loop creates a list particular for each book that shows both the championship (as a link to the yet-to-be-created particular view) and the author.

                                                                            <a                    href                                          =                      "{{ volume.get_absolute_url }}"                                        >                  {{ book.title }}                                          </a                    >                                    ({{book.author}})                              

We access the fields of the associated book record using the "dot note" (e.thou. book.title and book.writer), where the text following the book item is the field proper noun (as defined in the model).

We can also phone call functions in the model from within our template — in this case we phone call Book.get_absolute_url() to get a URL you lot could utilise to display the associated detail record. This works provided the office does not have any arguments (there is no way to laissez passer arguments!)

Note: We have to be a picayune careful of "side furnishings" when calling functions in templates. Here we just go a URL to display, simply a function can exercise pretty much annihilation — we wouldn't desire to delete our database (for example) only by rendering our template!

Update the base template

Open the base template (/locallibrary/catalog/templates/base_generic.html ) and insert {% url 'books' %} into the URL link for All books, equally shown below. This volition enable the link in all pages (nosotros can successfully put this in place now that we've created the "books" URL mapper).

                                  <li>                  <a href=                  "{% url 'index' %}"                  >Home<                  /a>                  <                  /li>                  <li>                  <a href=                  "{% url 'books' %}"                  >All books<                  /a>                  <                  /li>                  <li>                  <a href=                  ""                  >All authors<                  /a>                  <                  /li>                              

What does information technology look similar?

You won't be able to build the book list however, because we're nevertheless missing a dependency — the URL map for the book detail pages, which is needed to create hyperlinks to individual books. We'll show both list and detail views after the adjacent department.

Book particular page

The book detail folio volition brandish information about a specific book, accessed using the URL catalog/book/<id> (where <id> is the primary key for the book). In addition to fields in the Volume model (author, summary, ISBN, language, and genre), we'll likewise listing the details of the available copies (BookInstances) including the status, expected return appointment, imprint, and id. This volition let our readers to not just larn about the book, just also to confirm whether/when it is available.

URL mapping

Open up /catalog/urls.py and add the path named 'volume-detail' shown below. This path() function defines a blueprint, associated generic class-based item view, and a name.

                urlpatterns                  =                  [                  path(                  ''                  ,                  views.index,                  name=                  'alphabetize'                  )                  ,                  path(                  'books/'                  ,                  views.BookListView.as_view(                  )                  ,                  name=                  'books'                  )                  ,                  path(                  'book/<int:pk>'                  ,                  views.BookDetailView.as_view(                  )                  ,                  name=                  'book-detail'                  )                  ,                  ]                              

For the book-detail path the URL pattern uses a special syntax to capture the specific id of the book that nosotros want to see. The syntax is very unproblematic: angle brackets ascertain the part of the URL to be captured, enclosing the proper name of the variable that the view can use to access the captured data. For example, <something> , will capture the marked design and pass the value to the view equally a variable "something". You tin optionally precede the variable name with a converter specification that defines the type of information (int, str, slug, uuid, path).

In this case we utilize '<int:pk>' to capture the book id, which must be a specially formatted string and pass it to the view as a parameter named pk (short for primary primal). This is the id that is being used to store the book uniquely in the database, as defined in the Volume Model.

Note: Every bit discussed previously, our matched URL is really catalog/book/<digits> (because we are in the catalog application, /catalog/ is assumed).

Warning: The generic class-based detail view expects to exist passed a parameter named pk. If you're writing your own part view you can use any parameter proper name you like, or indeed pass the information in an unnamed statement.

Avant-garde path matching/regular expression primer

Note: Y'all won't demand this department to complete the tutorial! We provide it because knowing this option is likely to be useful in your Django-centric futurity.

The pattern matching provided by path() is simple and useful for the (very common) cases where you but want to capture any string or integer. If you need more refined filtering (for instance, to filter only strings that have a certain number of characters) then y'all can utilise the re_path() method.

This method is used just like path() except that it allows you lot to specify a pattern using a Regular expression. For example, the previous path could accept been written every bit shown below:

                re_path(                  r'^book/(?P<pk>\d+)$'                  ,                  views.BookDetailView.as_view(                  )                  ,                  proper noun=                  'volume-detail'                  )                  ,                              

Regular expressions are an incredibly powerful pattern mapping tool. They are, frankly, quite unintuitive and can be intimidating for beginners. Beneath is a very brusque primer!

The get-go thing to know is that regular expressions should ordinarily exist declared using the raw string literal syntax (i.e. they are enclosed every bit shown: r'<your regular expression text goes hither>').

The primary parts of the syntax you will need to know for declaring the blueprint matches are:

Nearly other characters can be taken literally!

Let's consider a few real examples of patterns:

You tin can capture multiple patterns in the one lucifer, and hence encode lots of different data in a URL.

Note: As a claiming, consider how you might encode a URL to list all books released in a detail twelvemonth, month, day, and the RE that could exist used to match it.

Passing additional options in your URL maps

One feature that we haven't used hither, but which you may find valuable, is that you tin can pass a dictionary containing additional options to the view (using the third un-named statement to the path() function). This approach tin exist useful if you want to utilise the same view for multiple resources, and pass information to configure its behavior in each case.

For case, given the path shown below, for a request to /myurl/halibut/ Django will call views.my_view(request, fish=halibut, my_template_name='some_path').

                path(                  'myurl/<int:fish>'                  ,                  views.my_view,                  {                  'my_template_name'                  :                  'some_path'                  }                  ,                  proper noun=                  'aurl'                  )                  ,                              

Note: Both named captured patterns and dictionary options are passed to the view as named arguments. If you use the same name for both a capture design and a dictionary key, and so the dictionary selection volition exist used.

View (course-based)

Open itemize/views.py, and copy the post-obit code into the bottom of the file:

                                  class                  BookDetailView                  (generic.DetailView)                  :                  model                  =                  Book                              

That's it! All y'all need to exercise now is create a template called /locallibrary/catalog/templates/itemize/book_detail.html, and the view will laissez passer it the database data for the specific Book record extracted by the URL mapper. Within the template you tin access the book'due south details with the template variable named object OR book (i.e. generically "the_model_name").

If you lot need to, you can change the template used and the name of the context object used to reference the book in the template. You lot can besides override methods to, for instance, add together boosted information to the context.

What happens if the record doesn't exist?

If a requested record does not exist then the generic class-based detail view volition raise an Http404 exception for you lot automatically — in production, this will automatically display an appropriate "resources not found" page, which you can customize if desired.

But to give y'all some idea of how this works, the code fragment below demonstrates how you would implement the class-based view as a function if you were not using the generic class-based detail view.

                                  def                  book_detail_view                  (request,                  primary_key)                  :                  try                  :                  book                  =                  Book.objects.become(pk=primary_key)                  except                  Book.DoesNotExist:                  heighten                  Http404(                  'Book does not exist'                  )                  return                  render(request,                  'catalog/book_detail.html'                  ,                  context=                  {                  'book'                  :                  book}                  )                              

The view start tries to get the specific volume tape from the model. If this fails the view should raise an Http404 exception to indicate that the book is "not establish". The terminal step is then, as usual, to call render() with the template name and the book data in the context parameter (every bit a dictionary).

Alternatively, we can use the get_object_or_404() function as a shortcut to enhance an Http404 exception if the record is non found.

                                  from                  django.shortcuts                  import                  get_object_or_404                  def                  book_detail_view                  (request,                  primary_key)                  :                  book                  =                  get_object_or_404(Volume,                  pk=primary_key)                  return                  render(asking,                  'catalog/book_detail.html'                  ,                  context=                  {                  'book'                  :                  book}                  )                              

Creating the Detail View template

Create the HTML file /locallibrary/itemize/templates/itemize/book_detail.html and give information technology the below content. Every bit discussed above, this is the default template file name expected by the generic form-based item view (for a model named Book in an application named catalog).

                {% extends "base_generic.html" %}  {% block content %}                                                            <h1                    >                  Title: {{ book.title }}                                          </h1                    >                                                                              <p                    >                                                                              <strong                    >                  Author:                                          </strong                    >                                                                              <a                    href                                          =                      "                      "                                        >                  {{ book.author }}                                          </a                    >                                                                              </p                    >                                    <!-- author detail link not yet defined -->                                                            <p                    >                                                                              <strong                    >                  Summary:                                          </stiff                    >                                    {{ book.summary }}                                          </p                    >                                                                              <p                    >                                                                              <stiff                    >                  ISBN:                                          </stiff                    >                                    {{ volume.isbn }}                                          </p                    >                                                                              <p                    >                                                                              <strong                    >                  Language:                                          </strong                    >                                    {{ book.language }}                                          </p                    >                                                                              <p                    >                                                                              <strong                    >                  Genre:                                          </potent                    >                                    {{ book.genre.all|bring together:", " }}                                          </p                    >                                                                              <div                                          way                                              =                        "                                                  margin-left                          :20px;                          margin-height                          :20px                        "                                                              >                                                                              <h4                    >                  Copies                                          </h4                    >                                    {% for copy in book.bookinstance_set.all %}                                                            <hr                    >                                                                              <p                    class                                          =                      "{% if copy.status ==                      'a'                      %}text-success{% elif copy.condition ==                      'thousand'                      %}text-danger{% else %}text-alarm{% endif %}"                                        >                                    {{ copy.get_status_display }}                                                            </p                    >                                    {% if copy.condition != 'a' %}                                                            <p                    >                                                                              <stiff                    >                  Due to be returned:                                          </strong                    >                                    {{ re-create.due_back }}                                          </p                    >                                    {% endif %}                                                            <p                    >                                                                              <stiff                    >                  Imprint:                                          </potent                    >                                    {{ copy.banner }}                                          </p                    >                                                                              <p                    class                                          =                      "text-muted"                                        >                                                                              <strong                    >                  Id:                                          </strong                    >                                    {{ copy.id }}                                          </p                    >                                    {% endfor %}                                                            </div                    >                                    {% endblock %}                              

Annotation: The author link in the template above has an empty URL because we've not yet created an author particular page to link to. Once the detail page exists nosotros can become its URL with either of these two approaches:

  • Utilize the url template tag to reverse the 'author-detail' URL (defined in the URL mapper), passing it the author case for the volume:
                                                  <a href=                        "{% url 'author-detail' book.writer.pk %}"                        >                        {                        {                        book.author                        }                        }                        <                        /a>                                          
  • Call the author model'due south get_absolute_url() method (this performs the same reversing operation):
    <a href="{{ book.author.get_absolute_url }}">{{ book.author }}</a>                    

While both methods finer practise the same thing, get_absolute_url() is preferred because it helps you write more consistent and maintainable lawmaking (any changes just need to be done in ane place: the author model).

Though a piddling larger, almost everything in this template has been described previously:

  • We extend our base template and override the "content" cake.
  • We use provisional processing to determine whether or not to display specific content.
  • Nosotros use for loops to loop through lists of objects.
  • We access the context fields using the dot annotation (because we've used the detail generic view, the context is named volume; nosotros could also utilize "object")

The start interesting affair we oasis't seen before is the office book.bookinstance_set.all(). This method is "automagically" constructed by Django in order to return the set of BookInstance records associated with a particular Book.

                                  {                  %                  for                  copy                  in                  book.bookinstance_set.                  all                  %                  }                  <!-                  -                  code to iterate beyond each re-create/case of a book                  -                  -                  >                  {                  %                  endfor                  %                  }                              

This method is needed because you lot declare a ForeignKey (one-to many) field only in the "many" side of the human relationship (the BookInstance). Since y'all don't do anything to declare the relationship in the other ("ane") model, it (the Book) doesn't accept whatever field to get the set of associated records. To overcome this trouble, Django constructs an appropriately named "reverse lookup" function that you lot tin employ. The proper name of the function is constructed by lower-casing the model proper noun where the ForeignKey was declared, followed by _set (i.e. and so the function created in Volume is bookinstance_set()).

Annotation: Here nosotros use all() to get all records (the default). While yous can use the filter() method to go a subset of records in code, you tin can't do this directly in templates considering you can't specify arguments to functions.

Beware also that if yous don't define an social club (on your grade-based view or model), you will also run into errors from the evolution server similar this one:

[29/May/2017 18:37:53] "Go /catalog/books/?folio=1 HTTP/1.1" 200 1637 /foo/local_library/venv/lib/python3.5/site-packages/django/views/generic/listing.py:99: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <QuerySet [<Writer: Ortiz, David>, <Author: H. McRaven, William>, <Writer: Leigh, Melinda>]>   allow_empty_first_page=allow_empty_first_page, **kwargs)                

That happens because the paginator object expects to run across some Lodge Past being executed on your underlying database. Without it, it tin can't be sure the records existence returned are really in the right order!

This tutorial hasn't covered Pagination (yet!), simply since you can't use sort_by() and laissez passer a parameter (the same with filter() described higher up) you lot will have to cull between iii choices:

  1. Add a ordering within a class Meta annunciation on your model.
  2. Add a queryset attribute in your custom class-based view, specifying an order_by().
  3. Adding a get_queryset method to your custom class-based view and also specify the order_by().

If you determine to become with a course Meta for the Author model (probably non every bit flexible as customizing the class-based view, but piece of cake plenty), you will finish up with something similar this:

                                      class                    Author                    (models.Model)                    :                    first_name                    =                    models.CharField(max_length=                    100                    )                    last_name                    =                    models.CharField(max_length=                    100                    )                    date_of_birth                    =                    models.DateField(null=                    True                    ,                    bare=                    True                    )                    date_of_death                    =                    models.DateField(                    'Died'                    ,                    null=                    True                    ,                    blank=                    True                    )                    def                    get_absolute_url                    (self)                    :                    return                    reverse(                    'author-detail'                    ,                    args=                    [                    str                    (self.                    id                    )                    ]                    )                    def                    __str__                    (self)                    :                    render                                          f'                                              {self.last_name}                                            ,                                                                    {self.first_name}                                            '                                        class                    Meta                    :                    ordering                    =                    [                    'last_name'                    ]                                  

Of course, the field doesn't demand to be last_name: information technology could be whatsoever other.

Terminal but non least, you lot should sort by an attribute/cavalcade that actually has an index (unique or not) on your database to avert performance bug. Of grade, this will not be necessary here (we are probably getting ahead of ourselves with and so few books and users), but it is something worth keeping in listen for future projects.

The second interesting (and not-obvious) matter in the template is where we set a class (text-success, text-danger, text-alarm) to color-lawmaking the human readable status text for each book instance ("bachelor", "maintenance", etc.). Acute readers will annotation that the method BookInstance.get_status_display() that nosotros apply to get the condition text does not appear elsewhere in the lawmaking.

                                  <p                  class                  =                  "{% if copy.status == 'a' %}text-success{% elif re-create.status == 'm' %}text-danger{% else %}text-alarm{% endif %}"                  >                  {                  {                  copy.get_status_display                  }                  }                  <                  /p>                              

This role is automatically created because BookInstance.condition is a choices field. Django automatically creates a method get_FOO_display() for every choices field "Foo" in a model, which can be used to get the current value of the field.

What does information technology look like?

At this betoken, we should have created everything needed to display both the volume list and volume detail pages. Run the server (python3 manage.py runserver) and open up your browser to http://127.0.0.1:8000/.

Warning: Don't click whatsoever author or author detail links nevertheless — you lot'll create those in the claiming!

Click the All books link to display the list of books.

Book List Page

Then click a link to one of your books. If everything is fix up correctly, you lot should encounter something like the following screenshot.

Book Detail Page

If yous've just got a few records, our volume list folio will look fine. However, every bit you become into the tens or hundreds of records the page will take progressively longer to load (and have far likewise much content to browse sensibly). The solution to this problem is to add pagination to your list views, reducing the number of items displayed on each page.

Django has fantabulous inbuilt support for pagination. Even improve, this is congenital into the generic grade-based list views then you lot don't have to do very much to enable information technology!

Views

Open up itemize/views.py, and add the paginate_by line shown below.

                                  class                  BookListView                  (generic.ListView)                  :                  model                  =                  Book     paginate_by                  =                  x                              

With this add-on, as soon equally you have more than than 10 records the view will get-go paginating the information it sends to the template. The dissimilar pages are accessed using Become parameters — to access page 2 you would apply the URL /catalog/books/?page=ii.

Templates

Now that the data is paginated, nosotros need to add together support to the template to gyre through the results fix. Because we might want paginate all list views, nosotros'll add this to the base template.

Open /locallibrary/catalog/templates/base_generic.html and find the "content block" (as shown below).

                                  {                  %                  block content                  %                  }                  {                  %                  endblock                  %                  }                              

Copy in the following pagination block immediately following the {% endblock %}. The code get-go checks if pagination is enabled on the current folio. If then, it adds next and previous links as appropriate (and the current page number).

                                  {                  %                  cake pagination                  %                  }                  {                  %                  if                  is_paginated                  %                  }                  <div                  class                  =                  "pagination"                  >                  <span                  course                  =                  "page-links"                  >                  {                  %                  if                  page_obj.has_previous                  %                  }                  <a href=                  "{{ asking.path }}?folio={{ page_obj.previous_page_number }}"                  >previous<                  /a>                  {                  %                  endif                  %                  }                  <span                  course                  =                  "page-current"                  >                  Folio                  {                  {                  page_obj.number                  }                  }                  of                  {                  {                  page_obj.paginator.num_pages                  }                  }                  .                  <                  /bridge>                  {                  %                  if                  page_obj.has_next                  %                  }                  <a href=                  "{{ request.path }}?folio={{ page_obj.next_page_number }}"                  >                  next                  <                  /a>                  {                  %                  endif                  %                  }                  <                  /span>                  <                  /div>                  {                  %                  endif                  %                  }                  {                  %                  endblock                  %                  }                              

The page_obj is a Paginator object that will exist if pagination is beingness used on the electric current page. It allows you to get all the information well-nigh the current page, previous pages, how many pages there are, etc.

Nosotros utilise {{ request.path }} to get the current page URL for creating the pagination links. This is useful because it is independent of the object that we're paginating.

That's it!

What does it look like?

The screenshot below shows what the pagination looks like — if you haven't entered more than x titles into your database, then you tin can examination information technology more than easily by lowering the number specified in the paginate_by line in your catalog/views.py file. To get the beneath result nosotros inverse it to paginate_by = 2.

The pagination links are displayed on the bottom, with adjacent/previous links beingness displayed depending on which page you're on.

Book List Page - paginated

Challenge yourself

The claiming in this article is to create the writer detail and listing views required to complete the project. These should exist fabricated available at the following URLs:

  • catalog/authors/ — The listing of all authors.
  • itemize/author/<id> — The particular view for the specific author with a principal key field named <id>

The code required for the URL mappers and the views should be virtually identical to the Book listing and particular views we created above. The templates will be different simply will share similar beliefs.

Notation:

  • Once you've created the URL mapper for the author list folio you will also need to update the All authors link in the base of operations template. Follow the same process as we did when we updated the All books link.
  • Once y'all've created the URL mapper for the writer particular page, you should besides update the volume detail view template (/locallibrary/catalog/templates/itemize/book_detail.html) so that the author link points to your new writer item folio (rather than existence an empty URL). The recommended way to do this is to call get_absolute_url() on the writer model as shown beneath.
                                                                                                        <p                          >                                                                                                      <potent                          >                        Author:                                                      </strong                          >                                                                                                      <a                          href                                                      =                            "{{ book.author.get_absolute_url }}"                                                    >                        {{ book.author }}                                                      </a                          >                                                                                                      </p                          >                                                                  

When you are finished, your pages should await something similar the screenshots beneath.

Author List Page

Author Detail Page

Summary

Congratulations, our bones library functionality is at present complete!

In this article, we've learned how to utilize the generic class-based list and detail views and used them to create pages to view our books and authors. Forth the manner we've learned nigh blueprint matching with regular expressions, and how you tin laissez passer information from URLs to your views. We've also learned a few more than tricks for using templates. Last of all we've shown how to paginate list views so that our lists are manageable even when nosotros accept many records.

In our next articles, we'll extend this library to back up user accounts, and thereby demonstrate user authentication, permissions, sessions, and forms.

Come across also

In this module

  • Django introduction
  • Setting upwards a Django development surroundings
  • Django Tutorial: The Local Library website
  • Django Tutorial Part ii: Creating a skeleton website
  • Django Tutorial Office three: Using models
  • Django Tutorial Part 4: Django admin site
  • Django Tutorial Part 5: Creating our home page
  • Django Tutorial Part 6: Generic list and detail views
  • Django Tutorial Office 7: Sessions framework
  • Django Tutorial Function 8: User hallmark and permissions
  • Django Tutorial Part 9: Working with forms
  • Django Tutorial Part 10: Testing a Django web application
  • Django Tutorial Part 11: Deploying Django to product
  • Django web application security
  • DIY Django mini web log

Source: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views

Posted by: baileybarriver.blogspot.com

0 Response to "How To Add All Values In A Column In Django Template Tags"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel