无法重定向到另一个视图/网址

时间:2017-09-06 11:52:19

标签: python django url redirect url-redirection

我有django应用程序(1.8),我希望在点击以下链接后从BookingRedirect重定向到ArchiveListView

<a href="{% url 'archive:list' %}" title="{% trans 'Archive' %}">
    {% trans 'Archive' %}
</a>

我收到了这个错误:

Reverse for 'archives' with arguments '()' and keyword arguments '{'kwargs': {'year': '2014', 'month': '1'}}' not found. 1 pattern(s) tried: ['en/archive/(?P<year>[0-9]{4})/(?P<month>[0-9]+)$']

我的观点我希望将其重定向到另一个带有其他视图的网址:

from django.shortcuts import redirect


class BookingRedirect(RedirectView):
    permanent = False

    def get_redirect_url(self, *args, **kwargs):
        return redirect('archive:archives', kwargs={'year': '2014', 'month': '1'})

网址:

urlpatterns = [
    url('^$', views.BookingRedirect.as_view(), name="list"),
    url(r'^/(?P<year>[0-9]{4})/(?P<month>[0-9]+)$', views.ArchiveListView.as_view(), name="archives"),
]

1 个答案:

答案 0 :(得分:1)

这不是你如何将kwargs传递给redirect函数。你直接将它们作为kwargs传递:

return redirect('archive:archives', year='2014', month='1')

请参阅the docs

但请注意,您的get_redirect_url应该根本不使用该功能。它需要返回视图本身随后重定向到的URL。所以你需要使用reverse,其中 以您使用的格式获取kwargs:

return reverse('archive:archives', kwargs={'year': '2014', 'month': '1'})