Django上的NoReverseMatch即使提供了kwargs也是如此

时间:2017-09-27 13:34:43

标签: django django-views django-urls django-1.8 django-1.11

Django无法恢复网址,即使提供了预期的kwarg。

这是root urls.py:

from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^media/(?P<path>.*)$','django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
    url(r'^ckeditor/', include('ckeditor_uploader.urls')),
    url(r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root': settings.STATIC_ROOT}),
    url(r'^(?P<domain>\w+)', include('frontend.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

这是frontend urls.py: 来自django.conf.urls import include,patterns,url

from . import views
from .views import MyprofileView
from .views import SuccessView
from .views import CompanyView
from .views import SubscriptionView


from django.views.decorators.csrf import csrf_exempt

urlpatterns = patterns('',
    url(r'/success(/?)$', SuccessView.as_view(), name='success'),
    url(r'/subscribe(/?)$', SubscriptionView.as_view(), name='subscribe'),
    url(r'^(/?)$', MyprofileView.as_view(), name='home'),
    url(r'/api/v1/', include('cpprofile.api.urls')),
    url(r'/product', include('product_information.urls')),
    url(r'/corporations/(?P<company>\d+)$', CompanyView.as_view(), name='company_page'),
    url(r'^/(?P<subscription>\w+)/product/pay/return/(?P<amount>\d+)/(?P<currency>\w+)/(?P<id>\d+)?$',
        views.payment_return, name='subscription_product_payment_return'),
)

以下是我试图在view.py MyprofileView中调用它的方法:

context['subscribe_url'] = redirect('subscribe', kwargs={'domain': 'up'})

这里可能有什么问题?

由于

更新1

以下是我遇到的错误:

django.core.urlresolvers.NoReverseMatch

NoReverseMatch: Reverse for 'subscribe' with arguments '()' and keyword arguments '{'domain': 'up'}' not found. 1 pattern(s) tried: ['(?P<domain>\\w+)/subscribe(/?)$']

3 个答案:

答案 0 :(得分:2)

您必须解压缩kwargs

<强>解决方案

kwargs = {'domain': 'up'}
redirect('app_name:subscribe', **kwargs)

编辑:这将有效,无需更改网址 EDIT2:将应用程序的名称和冒号添加到网址名称。这会在app命名空间中找到url。

参考:Redirect in Django

答案 1 :(得分:1)

我怀疑这是因为<div class="full-page login-page" data-color="blue" data-image="./assets/img/hola.jpg"> 。这会捕获(/?)''。因此,您必须将其作为非关键字参数传递:

'/'

所以这是Sachin Kukreja所说的。

答案 2 :(得分:1)

您需要使用reverse来获取正确的URL,然后重定向到该URL。

from django.core.urlresolvers import reverse

return redirect(reverse('subscribe', kwargs={'domain': 'up'}))

在您的情况下,您似乎尝试将url分配给上下文变量,您根本不应该使用重定向。反向解析URL,重定向返回响应。

context['subscribe_url'] = reverse('subscribe', kwargs={'domain': 'up'})

也可能希望在urlconf中遵循最佳实践以保持一致性,即使用'/'结束所有模式,但不要以'/'开头。正如你在root配置中为大多数人所做的那样:

url(r'^admin/', include(admin.site.urls)), <-- good