django - 在 MonthArchiveView 中默认为当前月份

标签 django django-views django-generic-views

我有一个 MonthArchiveView 用于我网站上的事件。如果没有提交年份和月份(例如,如果用户仅访问/events/?

# urls.py
url(r'^events/$', EventMonthView.as_view(), name="event_month"),
url(r'^events/(?P<year>[0-9]{4})/(?P<month>[0-9]+)/$', EventMonthView.as_view(month_format='%m'), name="event_month"),

#views.py
class EventMonthView(MonthArchiveView):
    template_name = "events.html"
    queryset = Event.objects.all()
    date_field = "date"
    allow_future = True
    month_format='%m'
    year_format='%Y'

最佳答案

您可以覆盖 get_monthget_year 方法,以便它们返回默认值:

from django.http import Http404
from django.utils.timezone import now
from django.views.generic import MonthArchiveView


class EventMonthView(MonthArchiveView):
    # ...

    def get_month(self):
        try:
            month = super(EventMonthView, self).get_month()
        except Http404:
            month = now().strftime(self.get_month_format())

        return month

    def get_year(self):
        try:
            year = super(EventMonthView, self).get_year()
        except Http404:
            year = now().strftime(self.get_year_format())

        return year

关于django - 在 MonthArchiveView 中默认为当前月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37376756/

相关文章:

python - Django ·奥斯卡。如何添加产品?

python - Django 在数据库中看不到用户?

Django 表单前缀与基于类的通用 View

python - url 调度程序使用正则表达式检测所有内容或不检测任何内容

python - 如何在运行django开发服务器时隐藏控制台?

Django根据外键对字段求和

python - Django - 在 DetailView 中过滤

python - 使用django提交后如何保留html表单数据?

python - GAE 是否支持 django 管理表单