【问题标题】:Django - reversing wrapped view functionsDjango - 反转包装的视图函数
【发布时间】:2010-01-19 19:16:47
【问题描述】:

我正在尝试将 django-schedule 合并到我的项目中。 Django-schedule 的来源是here。我不喜欢这些网址,因为它们都捕获了一个蛞蝓。我的项目将只允许每个用户使用一个日历,因此捕获 sl 没有意义。所以,我像这样包装了 django-schedule 视图(使用当前用户查找 slug,并将其传递给 django-schedule 的视图):

from schedule.views import calendar_by_periods
from schedule.models import Calendar
from schedule.periods import Month

def cal_by_periods_wrapper(view):
    def new_view(request, *args, **kwargs):
        kwargs['calendar_slug'] = Calendar.objects.get_calendars_for_object(obj=request.user, distinction="owner")[0].slug
        return view(request, *args, **kwargs)
    return new_view

这里是 urls.py 中的相关部分:

urlpatterns = patterns('',
                url(r'^$',
                    cal_by_periods_wrapper(calendar_by_periods),
                           name = "month_calendar",
                           kwargs={'periods': [Month], 'template_name': 'schedule/calendar_month.html'}),

这工作正常,直到它遇到 django-schedule 中包含的模板标签之一,prev_url:

@register.simple_tag
def prev_url(target, slug, period):
    return '%s%s' % (
        reverse(target, kwargs=dict(calendar_slug=slug)),
            querystring_for_date(period.prev().start))

这个函数引发:

TemplateSyntaxError at /teacher/calendar/

Caught an exception while rendering: Reverse for 'month_calendar' with arguments 
'()' and keyword arguments '{'calendar_slug': u'asdf'}' not found.

我怎样才能包装这个视图并且仍然使反向调用工作?

【问题讨论】:

    标签: django exception view wrapper reverse


    【解决方案1】:

    这与包装函数无关。只是您不再有一个名为“month_calendar”的 URL,它带有一个“calendar_slug”参数。在你的 urlconf 中定义一个,或者编辑模板标签。

    评论后编辑 是的,但是'reverse' 调用仍然传递一个slug 参数,并且没有'month_calendar' url 需要一个,所以反向匹配失败。

    【讨论】:

    • 我认为这就是我的 urls.py 中的 name = "month_calendar" 的用途......关键是我正试图从 url 中删除 calendar_slug。我错过了什么吗?
    • 好的,对不起,这对我来说是有意义的。我认为它抱怨的参数是视图函数的参数,而不是 URL。所以,真的,我唯一的选择是修改模板标签以不传递 slugs。知道了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 2016-11-09
    • 2018-12-12
    • 2023-02-07
    相关资源
    最近更新 更多