从django中的views.py重定向到另一个URL时发生NoReverseMatch错误

时间:2017-08-22 11:02:02

标签: python django redirect

我尝试在注册完成后重定向用户并获得以下错误。

Reverse for 'verificationsent' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

urls.py -

urlpatterns = [
    url(r'^ciasadmin/', admin.site.urls),
    url("^$", views.homepage, name="home"),
    url(r'^account/', include('accounts.urls')),
]

accounts / urls.py -

from django.conf.urls import url
from . import views


urlpatterns = [
    url(r"^signup/$", views.signup, name="account_signup"),
    url(r'^verificationsent/$', views.verificationsent, name='account_verificationsent'),
    url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',views.activate, name='activate'),
]

views.py -

return redirect('verificationsent')

完整追溯

Internal Server Error: /account/signup/
Traceback (most recent call last):
  File "C:\virtualenvs\ciasenv\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "C:\virtualenvs\ciasenv\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\virtualenvs\ciasenv\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\pyprojects\cias\ciasproj\accounts\views.py", line 41, in signup
    return redirect('verificationsent')
  File "C:\virtualenvs\ciasenv\lib\site-packages\django\shortcuts.py", line 56, in redirect
    return redirect_class(resolve_url(to, *args, **kwargs))
  File "C:\virtualenvs\ciasenv\lib\site-packages\django\shortcuts.py", line 147, in resolve_url
    return reverse(to, args=args, kwargs=kwargs)
  File "C:\virtualenvs\ciasenv\lib\site-packages\django\urls\base.py", line 91, in reverse
    return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  File "C:\virtualenvs\ciasenv\lib\site-packages\django\urls\resolvers.py", line 392, in _reverse_with_prefix
    (lookup_view_s, args, kwargs, len(patterns), patterns)
django.urls.exceptions.NoReverseMatch: Reverse for 'verificationsent' with arguments '()' and keyword arguments '{}' not
 found. 0 pattern(s) tried: []
[22/Aug/2017 10:22:00] "POST /account/signup/ HTTP/1.1" 500 88145

我已经按照以下SO参考文献中的解决方案进行了操作,但没有成功。

Redirect with parameters. NoReverseMatch at /test/

Django NoReverseMatch in form redirect

非常感谢任何帮助。提前谢谢。

1 个答案:

答案 0 :(得分:1)

根据最佳做法,您不应使用直接网址引用语句。始终reverse网址

return redirect(reverse('account_verificationsent'))

如果你的应用程序有一个命名空间,那么你也必须反过来使用它。