Django No Reverse Match with Arguments

时间:2023-01-13 19:57:09

From my template:

从我的模板:

<a href="{% url 'tracker:othermonth' year next_month %}">July</a>

URL Pattern:

url(r'^ocal/$', views.calendar, name = "othermonth"),

View:

def calendar(request, year, month):
    my_year = int(year)
    my_month = int(month)
    my_calendar_from_month = datetime(my_year, my_month, 1)
    my_calendar_to_month = datetime(my_year, my_month, monthrange(my_year, my_month)[1])

    my_tickets = Event.objects.filter(on_sale__gte=my_calendar_from_month).filter(on_sale__lte=my_calendar_to_month)

    my_previous_year = my_year
    my_previous_month = my_month - 1
    if my_previous_month == 0:
        my_previous_year = my_year - 1
        my_previous_month = 12
    my_next_year = my_year
    my_next_month = my_month + 1
    if my_next_month == 13:
        my_next_year = my_year + 1
        my_next_month = 1
    my_year_after_this = my_year + 1
    my_year_before_this = my_year - 1

    cal = TicketCalendar(my_tickets).formatmonth(year, month)

    return render_to_response('calendar.html', {'events_list': my_tickets,
                                                'calendar': mark_safe(cal),
                                                'month': my_month,
                                                'month_name': named_month(my_month),
                                                'year': my_year,
                                                'previous_month': my_previous_month,
                                                'previous_month_name': named_month(my_previous_month),
                                                'previous_year': my_previous_year,
                                                'next_month': my_next_month,
                                                'next_month_name': named_month(my_next_month),
                                                'next_year': my_next_year,
                                                'year_before_this': my_year_before_this,
                                                'year_after_this': my_year_after_this,
    }, context_instance=RequestContext(request))

Error:

Reverse for 'othermonth' with arguments '(2013, 7)' and keyword arguments '{}' not found.

I've searched through * and the django documentation but I can't seem to figure out why I'm getting this NoReverseMatch error. I'm sure its a very simple oversight on my part because I'm staring at code from a previous project which is almost identical to this and that works fine. Any help would be appreciated, thanks.

我已经搜索了*和django文档,但我似乎无法弄清楚为什么我得到这个NoReverseMatch错误。我确信这对我来说是一个非常简单的疏忽,因为我正在盯着前一个项目的代码,这个代码与此几乎相同,并且工作正常。任何帮助将不胜感激,谢谢。

UPDATE: I tried removing the parameters that I was trying to send with the URL and that fixed the NoReverseMatch however the view that is called requires those arguments so the link fails.

更新:我尝试删除我尝试使用URL发送的参数并修复了NoReverseMatch,但是调用的视图需要这些参数,因此链接失败。

2 个解决方案

#1


5  

How do you plan for those arguments to be embedded in your URL? There's nothing capturing them, and no way for the reverse lookup to construct it. You need a URL pattern that accepts these parameters. Something like:

您如何计划将这些参数嵌入到您的URL中?没有什么可以捕获它们,也没有办法进行反向查找来构建它。您需要一个接受这些参数的URL模式。就像是:

url(r'^ocal/(?P<year>\d{4})/(?P<month>(0|1)?\d)/$', views.calendar, name = "othermonth_bymonth"),

Using keyword rather than positional arguments here is optional, but I think it makes things easier - and allows setting default values that can trigger behavior like showing a calendar for the current day when nothing's specified.

在这里使用关键字而不是位置参数是可选的,但我认为它使事情变得更容易 - 并且允许设置可以触发行为的默认值,例如在没有指定任何内容时显示当天的日历。

Also, your mytickets queryset can also be constructed thus:

此外,您的mytickets查询集也可以这样构造:

mytickets = Event.objects.filter(on_sale__year=year, onsale__month=month)

Which I think is a little cleaner to read.

我认为阅读起来有点清洁。

Actually, upon a closer look - Django's built in date based views can do a lot of this for you. If you haven't already looked into them, I recommend doing so:

实际上,仔细看看 - Django内置的基于日期的视图可以为你做很多事情。如果你还没有调查过它们,我建议这样做:

https://docs.djangoproject.com/en/dev/ref/class-based-views/generic-date-based/

For this particular view, all you'd need to do is subclass MonthArchiveView to create your TicketCalendar instance and add it to your context.

对于此特定视图,您需要做的就是将MonthArchiveView子类化,以创建TicketCalendar实例并将其添加到您的上下文中。

Edit: OK, you're still getting problems. This is how I would go about solving this:

编辑:好的,你仍然遇到问题。这就是我要解决这个问题的方法:

views.py
class TicketMonthArchiveView(MonthArchiveView):
    allow_empty = True # show months even in which no tickets exist
    allow_future = True # show future months
    model = Event

    def get_context_data(self, **kwargs):
        base_context = super(TicketMonthArchiveView, self).get_context_data(**kwargs)
        my_tickets = kwargs['object_list']
        base_context['calendar'] = mark_safe(TicketCalendar(my_tickets).formatmonth(self.get_year(), self.get_month()))
        # the above could be a little off because I don't know exactly how your formatmonth method works
        return base_context

urls.py
    from somewhere.views import TicketMonthArchiveView
    # other patterns, plus:
    url(r'^ocal/(?P<year>\d{4})/(?P<month>(0|1)?\d)/$', TicketMonthArchiveView.as_view(), name='calendar_by_month'),

template event_archive_month.html
    <a href="{% url 'tracker:calendar_by_month' next_month|date:'%Y' next_month|date:'%m' %}">{{ next_month|date:'%f' }}</a>

Obviously there's a lot more you could do here with the year and day views, but this should demonstrate the general concepts.

显然,你可以用年和日视图做更多的事情,但这应该展示一般概念。

#2


0  

Large context volumes caused this behavior for me as well, despite having the correct syntax.

尽管具有正确的语法,但大的上下文卷也会对我造成这种行为。

I had this, on Django 1.5:

我有这个,在Django 1.5上:

urls.py

url(r'(?P<CLASSID>[A-Z0-9_]+)/$', 'psclassdefn.views.psclassdefn_detail', name="psclassdefn_detail"),

template.html

{% for inst in li_inst %}
<li><a href={% url 'psclassdefn.views.psclassdefn_detail' CLASSID=inst.CLASSID %}></a></li>
{% endfor %}

I kept on getting NoReverseMatch even though the syntax seemed OK and I could reverse into a no-argument url.

我继续获得NoReverseMatch,即使语法似乎没问题,我可以反转为无参数网址。

Now, li_inst was a huge list of about 1000 rows fetched from the db and passed to the context variable. Just to test, I trimmed the list by removing all but 10 or so rows. And it worked, without any syntax changes.

现在,li_inst是一个巨大的列表,其中包含从db获取的大约1000行并传递给上下文变量。为了测试,我通过删除除了10行之外的所有行来修剪列表。它工作正常,没有任何语法更改。

Maybe the templating system intentionally throttles the context size? I can filter the list if needed, just didn't expect this error to come from it.

也许模板系统故意限制上下文大小?如果需要,我可以过滤列表,只是不希望这个错误来自它。

#1


5  

How do you plan for those arguments to be embedded in your URL? There's nothing capturing them, and no way for the reverse lookup to construct it. You need a URL pattern that accepts these parameters. Something like:

您如何计划将这些参数嵌入到您的URL中?没有什么可以捕获它们,也没有办法进行反向查找来构建它。您需要一个接受这些参数的URL模式。就像是:

url(r'^ocal/(?P<year>\d{4})/(?P<month>(0|1)?\d)/$', views.calendar, name = "othermonth_bymonth"),

Using keyword rather than positional arguments here is optional, but I think it makes things easier - and allows setting default values that can trigger behavior like showing a calendar for the current day when nothing's specified.

在这里使用关键字而不是位置参数是可选的,但我认为它使事情变得更容易 - 并且允许设置可以触发行为的默认值,例如在没有指定任何内容时显示当天的日历。

Also, your mytickets queryset can also be constructed thus:

此外,您的mytickets查询集也可以这样构造:

mytickets = Event.objects.filter(on_sale__year=year, onsale__month=month)

Which I think is a little cleaner to read.

我认为阅读起来有点清洁。

Actually, upon a closer look - Django's built in date based views can do a lot of this for you. If you haven't already looked into them, I recommend doing so:

实际上,仔细看看 - Django内置的基于日期的视图可以为你做很多事情。如果你还没有调查过它们,我建议这样做:

https://docs.djangoproject.com/en/dev/ref/class-based-views/generic-date-based/

For this particular view, all you'd need to do is subclass MonthArchiveView to create your TicketCalendar instance and add it to your context.

对于此特定视图,您需要做的就是将MonthArchiveView子类化,以创建TicketCalendar实例并将其添加到您的上下文中。

Edit: OK, you're still getting problems. This is how I would go about solving this:

编辑:好的,你仍然遇到问题。这就是我要解决这个问题的方法:

views.py
class TicketMonthArchiveView(MonthArchiveView):
    allow_empty = True # show months even in which no tickets exist
    allow_future = True # show future months
    model = Event

    def get_context_data(self, **kwargs):
        base_context = super(TicketMonthArchiveView, self).get_context_data(**kwargs)
        my_tickets = kwargs['object_list']
        base_context['calendar'] = mark_safe(TicketCalendar(my_tickets).formatmonth(self.get_year(), self.get_month()))
        # the above could be a little off because I don't know exactly how your formatmonth method works
        return base_context

urls.py
    from somewhere.views import TicketMonthArchiveView
    # other patterns, plus:
    url(r'^ocal/(?P<year>\d{4})/(?P<month>(0|1)?\d)/$', TicketMonthArchiveView.as_view(), name='calendar_by_month'),

template event_archive_month.html
    <a href="{% url 'tracker:calendar_by_month' next_month|date:'%Y' next_month|date:'%m' %}">{{ next_month|date:'%f' }}</a>

Obviously there's a lot more you could do here with the year and day views, but this should demonstrate the general concepts.

显然,你可以用年和日视图做更多的事情,但这应该展示一般概念。

#2


0  

Large context volumes caused this behavior for me as well, despite having the correct syntax.

尽管具有正确的语法,但大的上下文卷也会对我造成这种行为。

I had this, on Django 1.5:

我有这个,在Django 1.5上:

urls.py

url(r'(?P<CLASSID>[A-Z0-9_]+)/$', 'psclassdefn.views.psclassdefn_detail', name="psclassdefn_detail"),

template.html

{% for inst in li_inst %}
<li><a href={% url 'psclassdefn.views.psclassdefn_detail' CLASSID=inst.CLASSID %}></a></li>
{% endfor %}

I kept on getting NoReverseMatch even though the syntax seemed OK and I could reverse into a no-argument url.

我继续获得NoReverseMatch,即使语法似乎没问题,我可以反转为无参数网址。

Now, li_inst was a huge list of about 1000 rows fetched from the db and passed to the context variable. Just to test, I trimmed the list by removing all but 10 or so rows. And it worked, without any syntax changes.

现在,li_inst是一个巨大的列表,其中包含从db获取的大约1000行并传递给上下文变量。为了测试,我通过删除除了10行之外的所有行来修剪列表。它工作正常,没有任何语法更改。

Maybe the templating system intentionally throttles the context size? I can filter the list if needed, just didn't expect this error to come from it.

也许模板系统故意限制上下文大小?如果需要,我可以过滤列表,只是不希望这个错误来自它。