Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Mastering Django: Core

You're reading from   Mastering Django: Core The Complete Guide to Django 1.8 LTS

Arrow left icon
Product type Paperback
Published in Dec 2016
Publisher
ISBN-13 9781787281141
Length 694 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Nigel George Nigel George
Author Profile Icon Nigel George
Nigel George
Arrow right icon
View More author details
Toc

Table of Contents (33) Chapters Close

Mastering Django: Core
Credits
About the Author
www.PacktPub.com
Preface
1. Introduction to Django and Getting Started FREE CHAPTER 2. Views and URLconfs 3. Templates 4. Models 5. The Django Admin Site 6. Forms 7. Advanced Views and URLconfs 8. Advanced Templates 9. Advanced Models 10. Generic Views 11. User Authentication in Django 12. Testing in Django 13. Deploying Django 14. Generating Non-HTML Content 15. Django Sessions 16. Djangos Cache Framework 17. Django Middleware 18. Internationalization 19. Security in Django 20. More on Installing Django 21. Advanced Database Management Model Definition Reference Database API Reference Generic View Reference Settings Built-in Template Tags and Filters Request and Response Objects Developing Django with Visual Studio

Date-Based Generic Views


Date-based generic views, provided in django.views.generic.dates, are views for displaying drilldown pages for date-based data.

ArchiveIndexView

A top-level index page showing the latest objects, by date. Objects with a date in the future are not included unless you set allow_future to True.

Context

In addition to the context provided by django.views.generic.list.MultipleObjectMixin (via django.views.generic.dates.BaseDateListView), the template's context will be:

  • date_list: A DateQuerySet object containing all years that have objects available according to queryset, represented as datetime.datetime objects, in descending order

Notes

  • Uses a default context_object_name of latest.
  • Uses a default template_name_suffix of _archive.
  • Defaults to providing date_list by year, but this can be altered to month or day using the attribute date_list_period. This also applies to all subclass views:
Example myapp/urls.py: 
from django.conf.urls import url 
from django.views.generic.dates import ArchiveIndexView 
 
from myapp.models import Article 
 
urlpatterns = [ 
    url(r'^archive/$', 
        ArchiveIndexView.as_view(model=Article, date_field="pub_date"), 
        name="article_archive"), 
] 

Example myapp/article_archive.html:

<ul> 
    {% for article in latest %} 
        <li>{{ article.pub_date }}: {{ article.title }}</li> 
    {% endfor %} 
</ul> 

This will output all articles.

YearArchiveView

A yearly archive page showing all available months in a given year. Objects with a date in the future are not displayed unless you set allow_future to True.

Context

In addition to the context provided by django.views.generic.list.MultipleObjectMixin (via django.views.generic.dates.BaseDateListView), the template's context will be:

  • date_list: A DateQuerySet object containing all months that have objects available according to queryset, represented as datetime.datetime objects, in ascending order
  • year: A date object representing the given year
  • next_year: A date object representing the first day of the next year, according to allow_empty and allow_future
  • previous_year: A date object representing the first day of the previous year, according to allow_empty and allow_future

Notes

  • Uses a default template_name_suffix of _archive_year

Example myapp/views.py:

from django.views.generic.dates import YearArchiveView 
 
from myapp.models import Article 
 
class ArticleYearArchiveView(YearArchiveView): 
    queryset = Article.objects.all() 
    date_field = "pub_date" 
    make_object_list = True 
    allow_future = True 

Example myapp/urls.py:

from django.conf.urls import url 
 
from myapp.views import ArticleYearArchiveView 
 
urlpatterns = [ 
    url(r'^(?P<year>[0-9]{4})/$', 
        ArticleYearArchiveView.as_view(), 
        name="article_year_archive"), 
] 

Example myapp/article_archive_year.html:

<ul> 
    {% for date in date_list %} 
        <li>{{ date|date }}</li> 
    {% endfor %} 
</ul> 
<div> 
    <h1>All Articles for {{ year|date:"Y" }}</h1> 
    {% for obj in object_list %} 
        <p> 
            {{ obj.title }}-{{ obj.pub_date|date:"F j, Y" }} 
        </p> 
    {% endfor %} 
</div> 

MonthArchiveView

A monthly archive page showing all objects in a given month. Objects with a date in the future are not displayed unless you set allow_future to True.

Context

In addition to the context provided by MultipleObjectMixin (via BaseDateListView), the template's context will be:

  • date_list: A DateQuerySet object containing all days that have objects available in the given month, according to queryset, represented as datetime.datetime objects, in ascending order
  • month: A date object representing the given month
  • next_month: A date object representing the first day of the next month, according to allow_empty and allow_future
  • previous_month: A date object representing the first day of the previous month, according to allow_empty and allow_future

Notes

  • Uses a default template_name_suffix of _archive_month

Example myapp/views.py:

from django.views.generic.dates import MonthArchiveView 
 
from myapp.models import Article 
 
class ArticleMonthArchiveView(MonthArchiveView): 
    queryset = Article.objects.all() 
    date_field = "pub_date" 
    make_object_list = True 
    allow_future = True 

Example myapp/urls.py:

from django.conf.urls import url 
 
from myapp.views import ArticleMonthArchiveView 
 
urlpatterns = [ 
    # Example: /2012/aug/ 
    url(r'^(?P<year>[0-9]{4})/(?P<month>[-\w]+)/$', 
        ArticleMonthArchiveView.as_view(), 
        name="archive_month"), 
    # Example: /2012/08/ 
    url(r'^(?P<year>[0-9]{4})/(?P<month>[0-9]+)/$', 
        ArticleMonthArchiveView.as_view(month_format='%m'), 
        name="archive_month_numeric"), 
] 

Example myapp/article_archive_month.html:

<ul> 
    {% for article in object_list %} 
        <li>{{ article.pub_date|date:"F j, Y" }}:  
            {{ article.title }} 
        </li> 
    {% endfor %} 
</ul> 
 
<p> 
    {% if previous_month %} 
        Previous Month: {{ previous_month|date:"F Y" }} 
    {% endif %} 
    {% if next_month %} 
        Next Month: {{ next_month|date:"F Y" }} 
    {% endif %} 
</p> 

WeekArchiveView

A weekly archive page showing all objects in a given week. Objects with a date in the future are not displayed unless you set allow_future to True.

Context

In addition to the context provided by MultipleObjectMixin (via BaseDateListView), the template's context will be:

  • week: A date object representing the first day of the given week
  • next_week: A date object representing the first day of the next week, according to allow_empty and allow_future
  • previous_week: A date object representing the first day of the previous week, according to allow_empty and allow_future

Notes

  • Uses a default template_name_suffix of _archive_week

Example myapp/views.py:

from django.views.generic.dates import WeekArchiveView 
 
from myapp.models import Article 
 
class ArticleWeekArchiveView(WeekArchiveView): 
    queryset = Article.objects.all() 
    date_field = "pub_date" 
    make_object_list = True 
    week_format = "%W" 
    allow_future = True 

Example myapp/urls.py:

from django.conf.urls import url 
 
from myapp.views import ArticleWeekArchiveView 
 
urlpatterns = [ 
    # Example: /2012/week/23/ 
    url(r'^(?P<year>[0-9]{4})/week/(?P<week>[0-9]+)/$', 
        ArticleWeekArchiveView.as_view(), 
        name="archive_week"), 
] 

Example myapp/article_archive_week.html:

<h1>Week {{ week|date:'W' }}</h1> 
 
<ul> 
    {% for article in object_list %} 
        <li>{{ article.pub_date|date:"F j, Y" }}: {{ article.title }}</li> 
    {% endfor %} 
</ul> 
 
<p> 
    {% if previous_week %} 
        Previous Week: {{ previous_week|date:"F Y" }} 
    {% endif %} 
    {% if previous_week and next_week %}--{% endif %} 
    {% if next_week %} 
        Next week: {{ next_week|date:"F Y" }} 
    {% endif %} 
</p> 

In this example, you are outputting the week number. The default week_format in the WeekArchiveView uses week format "%U" which is based on the United States week system where the week begins on a Sunday. The "%W" format uses the ISO week format and its week begins on a Monday. The "%W" format is the same in both the strftime() and the date.

However, the date template filter does not have an equivalent output format that supports the US based week system. The date filter "%U" outputs the number of seconds since the Unix epoch.

DayArchiveView

A day archive page showing all objects in a given day. Days in the future throw a 404 error, regardless of whether any objects exist for future days, unless you set allow_future to True.

Context

In addition to the context provided by MultipleObjectMixin (via BaseDateListView), the template's context will be:

  • day: A date object representing the given day
  • next_day: A date object representing the next day, according to allow_empty and allow_future
  • previous_day: A date object representing the previous day, according to allow_empty and allow_future
  • next_month: A date object representing the first day of the next month, according to allow_empty and allow_future
  • previous_month: A date object representing the first day of the previous month, according to allow_empty and allow_future

Notes

  • Uses a default template_name_suffix of _archive_day

Example myapp/views.py:

from django.views.generic.dates import DayArchiveView 
 
from myapp.models import Article 
 
class ArticleDayArchiveView(DayArchiveView): 
    queryset = Article.objects.all() 
    date_field = "pub_date" 
    make_object_list = True 
    allow_future = True 

Example myapp/urls.py:

from django.conf.urls import url 
 
from myapp.views import ArticleDayArchiveView 
 
urlpatterns = [ 
    # Example: /2012/nov/10/ 
    url(r'^(?P<year>[0-9]{4})/(?P<month>[-\w]+)/(?P<day>[0-9]+)/$', 
        ArticleDayArchiveView.as_view(), 
        name="archive_day"), 
] 

Example myapp/article_archive_day.html:

<h1>{{ day }}</h1> 
 
<ul> 
    {% for article in object_list %} 
        <li> 
        {{ article.pub_date|date:"F j, Y" }}: {{ article.title }} 
        </li> 
    {% endfor %} 
</ul> 
 
<p> 
    {% if previous_day %} 
        Previous Day: {{ previous_day }} 
    {% endif %} 
    {% if previous_day and next_day %}--{% endif %} 
    {% if next_day %} 
        Next Day: {{ next_day }} 
    {% endif %} 
</p> 

TodayArchiveView

A day archive page showing all objects for today. This is exactly the same as django.views.generic.dates.DayArchiveView, except today's date is used instead of the year/month/day arguments.

Notes

  • Uses a default template_name_suffix of _archive_today

Example myapp/views.py:

from django.views.generic.dates import TodayArchiveView 
 
from myapp.models import Article 
 
class ArticleTodayArchiveView(TodayArchiveView): 
    queryset = Article.objects.all() 
    date_field = "pub_date" 
    make_object_list = True 
    allow_future = True 

Example myapp/urls.py:

from django.conf.urls import url 
 
from myapp.views import ArticleTodayArchiveView 
 
urlpatterns = [ 
    url(r'^today/$', 
        ArticleTodayArchiveView.as_view(), 
        name="archive_today"), 
] 

Where is the example template for TodayArchiveView?

This view uses by default the same template as the DayArchiveView, which is in the previous example. If you need a different template, set the template_name attribute to be the name of the new template.

DateDetailView

A page representing an individual object. If the object has a date value in the future, the view will throw a 404 error by default, unless you set allow_future to True.

Context

  • Includes the single object associated with the model specified in the DateDetailView

Notes

  • Uses a default template_name_suffix of _detail
Example myapp/urls.py: 
from django.conf.urls import url 
from django.views.generic.dates import DateDetailView 
 
urlpatterns = [ 
    url(r'^(?P<year>[0-9]+)/(?P<month>[-\w]+)/(?P<day>[0-9]+)/ 
      (?P<pk>[0-9]+)/$', 
        DateDetailView.as_view(model=Article, date_field="pub_date"), 
        name="archive_date_detail"), 
] 

Example myapp/article_detail.html:

<h1>{{ object.title }}</h1> 
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime
Visually different images