url 没有 NoReverseMatch 的 kwargs 重定向

url redirect with kwargs no NoReverseMatch

主要项目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})

我不明白为什么会出现以下错误:

NoReverseMatch at /doll/

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

当然,当我在浏览器中硬访问 127.0.0.1:8000/yourdolldata/15/ 时,它工作得很好。所以这一切都是关于这个逆转过程。我想这与我的 url 正则表达式不匹配我认为我正在逆转的内容有关......

我怎样才能解决这个问题?我知道这是一个常见的错误,但在我完成互联网研究后,我看不出有任何错误的做法。

为附加到您要撤消的视图的 url 添加名称:

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 的视图名称作为第一个参数。