带有参数的URL上的Django NoReverseMatch

时间:2019-02-21 09:53:56

标签: python django django-urls

我在使用极其简单的表单视图(将单个值发布到重定向视图)中遇到麻烦。两种观点都是自己工作的。提交表单后,只有该特定视图失败。

views.py

def hsk_select(request, username=None):
    template_name = 'tests/hsklevelselect.html'
    if request.method == 'POST':
        form = HskLevelSelectForm(request.POST)
        if form.is_valid():
            level = form.cleaned_data['level']
            return redirect('tests:hsktest', level=level)
    else:
        form = HskLevelSelectForm()
    context = {
        'form': form,
        'username': username,
    }
    return render(request, template_name, context)

forms.py

class HskLevelSelectForm(forms.Form):
    level = forms.ChoiceField(choices=[(x, x) for x in range(1, 7)])

app / urls.py

from django.urls import path

from . import views

app_name = 'tests'

urlpatterns = [
    path('duolingo/', views.duolingo_test, name='duotest'),
    path('hsk/', views.hsk_select, name='hskselect'),
    path('hsk/<int:level>/', views.hsk_test, name='hsktest'),
]

project / urls.py

from django.urls import path

from . import views

app_name = 'main'

urlpatterns = [
    path('', views.enteruser, name='enteruser'),
    path('success/', views.success, name='success'),
    path('<str:username>/', views.home, name='home'),
]

跟踪

Environment:


Request Method: POST Request URL:
http://duotool.website.net/username/test/hsk/

Django Version: 2.1.5 Python Version: 3.5.2 Installed Applications:
['rest_framework',  'debug_toolbar',  'django.contrib.admin', 
'django.contrib.auth',  'django.contrib.contenttypes', 
'django.contrib.sessions',  'django.contrib.messages', 
'django.contrib.staticfiles',  'main',  'tests',  'widget_tweaks']
Installed Middleware:
['debug_toolbar.middleware.DebugToolbarMiddleware', 
'django.middleware.security.SecurityMiddleware', 
django.contrib.sessions.middleware.SessionMiddleware', 
'django.middleware.common.CommonMiddleware', 
'django.middleware.csrf.CsrfViewMiddleware', 
'django.contrib.auth.middleware.AuthenticationMiddleware', 
'django.contrib.messages.middleware.MessageMiddleware', 
'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File
"/var/www/django/duotool.website.net/venv/lib/python3.5/site-packages/django/core/handlers/exception.py"
in inner
  34.             response = get_response(request)

File
"/var/www/django/duotool.website.net/venv/lib/python3.5/site-packages/django/core/handlers/base.py"
in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File
"/var/www/django/duotool.website.net/venv/lib/python3.5/site-packages/django/core/handlers/base.py"
in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/var/www/django/duotool.website.net/duotool/tests/views.py" in hsk_select
  132.             return redirect('tests:hsktest', level=level)

File
"/var/www/django/duotool.website.net/venv/lib/python3.5/site-packages/django/shortcuts.py"
in redirect
  58.     return redirect_class(resolve_url(to, *args, **kwargs))

File
"/var/www/django/duotool.website.net/venv/lib/python3.5/site-packages/django/shortcuts.py"
in resolve_url
  148.         return reverse(to, args=args, kwargs=kwargs)

File
"/var/www/django/duotool.website.net/venv/lib/python3.5/site-packages/django/urls/base.py"
in reverse
  90.     return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))

File
"/var/www/django/duotool.website.net/venv/lib/python3.5/site-packages/django/urls/resolvers.py"
in _reverse_with_prefix
  622.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /username/test/hsk/ Exception Value:
Reverse for 'hsktest' with keyword arguments '{'level': '1'}' not found. 1 pattern(s) tried:
['(?P<username>[^/]+)\\/test\\/hsk\\/(?P<level>[0-9]+)\\/$']

我真的不确定这里到底发生了什么。我做的表格比这复杂得多。 >。<我在这里很想念什么?

2 个答案:

答案 0 :(得分:1)

您还没有显示如何在项目的URL中包括app/urls.py,但是回溯显示完整的URL模式包括用户名:

'(?P<username>[^/]+)\\/test\\/hsk\\/(?P<level>[0-9]+)\\/$'

因此,当您反转URL时,您需要包括用户名

redirect('tests:hsktest', username=request.user.username, level=level)

由于视图默认为username=None,因此您需要考虑这种情况下的操作。

答案 1 :(得分:0)

尝试一下:

urlpatterns = [
    path('duolingo/', views.duolingo_test, name='duotest'),
    path('hsk', views.hsk_select, name='hskselect'), # remove slash to distinguish the other url
    path('hsk/<int:level>/', views.hsk_test, name='hsktest'),
]