url重定向与kwargs没有NoReverseMatch

时间:2016-04-04 19:59:01

标签: python-3.x url django-1.9

main-project urls.py:

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

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'', include('data.urls')),
]

urls.py:

urlpatterns = [
    url(r'^doll/$', views.doll_describer),
    url(r'^yourdolldata/(?P<id>\d+)/$', views.yourDollData),
    url(r'^connexion/$', views.connexion),
    url(r'^logout/$', views.deconnexion),
]

views.py

def doll_describer(request):
        # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = DollForm(request.POST)
        print(form)
        # check whether it's valid:
        if form.is_valid():
            print("was valid")
            doll = form.save(commit=False)
            doll.save()
            print("DOG.ID=",doll.id)
            return HttpResponseRedirect(reverse('yourDollData', kwargs={'id': doll.id}))

        else : 
            print("form is not valid")

    # if a GET (or any other method) we'll create a blank form
    else:
        form = DollForm()
        print("wasn't valid")

    return render(request, 'data/doll.html', {'form':DollForm})

def yourDollData(request,id):
    doll = DollData.objects.get(id=id)
    print("Doll=",doll)
    print("DOG_TYPE=",type(doll))
    return render(request, 'data/save.html', {'doll': doll})

我无法理解为什么我会收到以下错误:

  

/ doll /

的NoReverseMatch

它涉及HttpResponseRedirect(reverse('yourDollData', kwargs={'id': doll.id})) 很难,一切都很好doll.id,之前正确打印出来。

当然,当我在浏览器中硬访问127.0.0.1:8000/yourdolldata/15/时,它的效果非常好。所以关于这个逆转过程。我想这跟我的网址正则表达式有什么关系,不符合我认为我正在倒转...

我怎样才能解决这个问题?我知道这是一个常见的错误,但在我完成我的网络研究后,我无法看到任何事情做错了。

1 个答案:

答案 0 :(得分:0)

为附加到您要反转的视图的网址添加名称:

url(r'^yourdolldata/(?P<id>\d+)/$', views.yourDollData, name='check_doll_data')

将以前的名称作为reverse函数的参数。

        return HttpResponseRedirect(reverse('check_doll_data',kwargs={'id': dog.id}))

Reverse可以将url,视图名称或附加到url的视图名称作为第一个参数。