开发者

next and previous week with Django 1.3 generic views week archive

I am new to Django and I would like to know how can I get the next and previous week links in my template using the week archive generic view. For the archive_month generic view there is a next_month and previous_month object in the template context but not for the archive_week generic view.

models.py

class Day(models.Model):
day = models.AutoField(primary_key=True)
date = models.DateField()
description = models.TextField()

def __unicode__(self):
    return str(self.day)

urls.py

week_info = {
"queryset" : Day.ob开发者_运维问答jects.order_by('-date'),
"date_field" : "date",
}

urlpatterns = patterns('journal.views',
(r'^(?P<year>\d{4})/(?P<week>\d{2})/$', date_based.archive_week, week_info),
)


You need two links: if current week is 33, previous should read 32, next 34.
Could you possibly grab the current week from the url from within the extra_context dictionary? The dictionary is iterated over after the week variable in generic view code itself, meaning you should have access to it directly in your urls.py (my suspicion)

The url grabs only numbers, but the view works with strings (line 201 in date_based.py):

try:
    tt = time.strptime(year+'-0-'+week, '%Y-%w-%U')
    date = datetime.date(*tt[:3])
except ValueError:
    raise Http404

time.strptime operates on strings, meaning that we need to turn them into integers, add or subtract one, and save those new values as keys in extra context. So I would add the following to your week_info dict:

"next_week" : int(week) + 1,
"prev_week" : int(week) - 1,

Since these links are meant to be args for other date based views, it's fine to leave them as integers. Then build your links from the newly passed context variables.

Hope this helps ;)


You can use the date filter to format the year and week number, and use it to get next and previous week links:

{% if previous_week %}
  {% with prev_week_year|date:"Y" prev_week=previous_week|date:"W" %}
    <a href="{% url <NAME_OF_YOUR_VIEW> prev_week_year prev_week %}">
      See Previous Week</a>
  {% endwith %}
{% endif %}
{% if previous_week and next_week %} | {% endif %}
{% if next_week %}
  {% with next_week_year|date:"Y" next_week=next_week|date:"W" %}
    <a href="{% url <NAME_OF_YOUR_VIEW> next_week_year next_week %}">
      See Next Week</a>
  {% endwith %}
{% endif %}

You'll also need to name your view.

Don't forget upgrade Django to a newer (more secure) release.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜