如何在特定日期之后更改URL解析的视图?

时间:2014-04-12 20:00:52

标签: django django-urls django-1.5 url-pattern django-formwizard

我正在撰写比赛应用。比赛在特定日期的午夜结束。我想让应用自动切换:使用CookieWizardView,来自formtools;来自通用视图库的正常TemplateView

目前我的urlpatterns的相关部分如下所示:

urlpatterns += patterns('',
    url(r'^$', 'appname.views.contest'), # the CookieWizardView
)

我喜欢在某个特定日期之后表现得好像这样:

urlpatterns += patterns('',
    url(r'^$', 'appname.views.contestclosed'), # a TemplateView
)

我完全,完全很好,有一个硬编码的幻数,我只是不想在那天午夜起床!

~~

我解决了这个问题,但无法回答我自己的问题,因为我太新了。

我在views.py

中创建了一个函数
def contest_switcher(request):
    if datetime.datetime.now() < datetime.datetime(YEAR_OVER, MONTH_OVER, DAY_OVER):
        return contest(request)
    else:
        return contestclosed(request)

这就是诀窍,现在我的urlpattern是:

urlpatterns += patterns('',
    url(r'^$', 'appname.views.contest_switcher'),
)

我确实必须在我的比赛结束视图中添加一个功能,因为它不期望发布POST,如果有人试图在午夜填写比赛表格,可能会发生这种情况:

class ContestClosedView(TemplateView):
    template_name = "appname/closed.html"

    def post(self, *args, **kwargs):
        return self.get(*args, **kwargs)

contestclosed = ContestClosedView.as_view()

1 个答案:

答案 0 :(得分:2)

你不必试图破解你的urls.py来解决这个问题。设置一个指向如下所示视图的URL模式:

def contest_page(request, contest_id):
    try:
        contest = Contest.objects.get(pk=contest_id)
    except Contest.DoesNotExist:
        raise Http404  # minimum necessary - you can do better
    if datetime.datetime.now() < contest.end_date:  # model field rather than module constants
        return contest(request, contest_id)  # CookieWizardView
    else:
        return contestclosed(request, contest_id)  # TemplateView

这基本上是你的contest_switcher有改进:

  • 适用于多个竞赛
  • 比赛知道他们自己的结束日期,因此您不会使用常量混乱您的模块范围
  • 简单urls.py并且视图执行委派所显示内容的工作(您知道,视图

(请注意,此示例意味着您将相应地更改模型并导入所有正确的库等。)