NoReverseMatch反向定义关键字参数不起作用

时间:2017-05-03 09:20:30

标签: python django url redirect arguments

我有两个Django视图,一个加载一个formset,一个提交它。这是为了避免重新提交表单或在POST后必须更改为其他视图。提交后,我重定向回加载formset的视图。但我无法让URL /反向工作。

以下是我的观点和网址

def view(request, model1_id):

    #load formsets

    #pass information to submit view
    request.session['model1_session'] = int(model1_id)

    return render(request, 'app/view.html')

def view_submit(request):
    #get the session
    model1_object = request.session.get('model1_session')
    ...
    if request.method == 'POST':
        #save formset
        #error!!!!
        return HttpResponseRedirect(reverse("app:view", kwargs={"model1_id":  "model1_object"}))


url(r'^(?P<model1_id>[0-9]+)/model1/something/$', views.view, name='view' ),
url(r'^model1/something/submit/$', views.view_submit, name='view_submit' ),

但是当我按下提交时,一切都保存得很好,但反过来也没有用......

Internal Server Error: /app/model1/something/submit/
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/username/Documents/Database/project/app/views.py", line 412, in view_submit
    return HttpResponseRedirect(reverse("app:view", kwargs={"model1_id":  "model1_object"}))
  File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py", line 600, in reverse
    return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py", line 508, in _reverse_with_prefix
    (lookup_view_s, args, kwargs, len(patterns), patterns))
NoReverseMatch: Reverse for 'view' with arguments '()' and keyword arguments '{'model1_id': 'model1_object'}' not found. 1 pattern(s) tried: [u'app/(?P<model1_id>[0-9]+)/model1/something/$']

我不明白为什么它不能接受kwargs?

class Model1(models.Model):

    ...

    def __str__(self):
        return unicode(self.id) or u''

    def get_absolute_url(self):
        #I think this is the problem... but I don't know how to solve it...
        return reverse('app:view', kwargs={'id': self.id})

...帮助...

1 个答案:

答案 0 :(得分:1)

您正在使用字符串"model1_object"而不是变量model1_object。尝试:

reverse("app:view", kwargs={"model1_id":  model1_object})

请注意,您可以使用redirect快捷方式而不是reverseHttpResponseRedirect来简化代码:

from django.shortcuts import redirect

return redirect("app:view", model1_id=model1_object)