【问题标题】:How to customize the URL of Date-based generic views?如何自定义基于日期的通用视图的 URL?
【发布时间】:2009-12-04 17:48:33
【问题描述】:

这是我的网址格式:

news_info_month_dict = {
    'queryset': Entry.published.filter(is_published=True),
    'date_field': 'pub_date',
    'month_format': '%m',
}

(r'^(?P<category>[-\w]+)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+).html$', 
    'object_detail', news_info_month_dict, 'news_detail'),

但他们有这样的错误:

object_detail() got an unexpected keyword argument 'category'

请帮助我。谢谢!

【问题讨论】:

    标签: django django-urls django-views


    【解决方案1】:

    我认为您必须编写自己的视图来代替通用的 object_detail,类似这样(未经测试)

    import datetime
    
    def view_entry(request, category, year, month, day, slug):
        date = datetime.date(int(year), int(month), int(day))
        entry = get_object_or_404(Entry, slug=slug, date=date, is_published=True, category=category)
        return render_to_response('news_detail', {'object': entry})
    

    虽然有可能使用object_detail 来做到这一点我不知道 - 我很少使用通用视图。

    【讨论】:

    • 抱歉,函数 datetime.date 不接受变量。他们想要整数。
    【解决方案2】:

    在您的 URL 正则表达式中,&lt;brackets&gt; 中的所有内容都作为关键字参数传递给通用视图。

    问题是您使用的通用视图 (object_detail) 不支持所有这些参数(即 category)。

    More information about the object_detail generic view and the arguments it accepts.

    如果您需要 category 参数,只需按照 Nick 上面的建议包装视图并从您的 URLconf 中调用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-08
      • 2012-01-28
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 2013-06-21
      • 2011-11-14
      • 2011-08-06
      相关资源
      最近更新 更多