呈现Django时出现NoReverseMatch错误

时间:2017-12-05 08:59:53

标签: django rendering

以下是我的views.py. POST后,用户获得一个显示5个项目的成功页面。同时我还想向用户显示environment。所以我做了类似下面的事情(传递environment作为参数)。我在redirect发生时得到了它,它试图找到类似successenvironment参数匹配的内容,但它无法获得。可能我需要  正确的正则表达式处理这个,我不知道如何处理这个问题。

def order_create(request):
    cart = ItemObject.objects.all()

    if request.method == 'POST':
        ...
            environment = envi_dict1.difference(item_dict1)
            return HttpResponseRedirect(reverse('success', {'environment': environment}))

    else:
        form = ItemObjectCreateForm()
    return render(request,
                  'index.html',
                  {'form': form})

def successView(request):

    return render(request, 'success.html', {'items': ItemObject.objects.filter(gp_code='Unknown')[:5]})

urls.py

urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^export_action/', include("export_action.urls", namespace="export_action")),
    url('^business-logic/', include('business_logic.urls')),
    url('^index/', views.order_create),
    url(r'^success/', views.successView, name='success')
]

我得到的错误就是这个

NoReverseMatch at /index/
Reverse for 'success' with keyword arguments '{u'environment': set([u'Test1'])}' not found. 1 pattern(s) tried: ['success/']

2 个答案:

答案 0 :(得分:0)

尝试

return HttpResponseRedirect(reverse('success/', {'environment': environment}))

你的网址有' /'成功

url(r'^success/', views.successView, name='success')

但没有给予' /'在重定向网址

答案 1 :(得分:0)

我使用了Sandeep的想法,即将变量存储在会话中。在views.py下我有request.session['environment'] = environment,在success.html下,我使用request.session.environment