Search code examples
python-3.xurldjango-1.9

url redirect with kwargs no NoReverseMatch


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})

I can't understand why i'm getting the following error :

NoReverseMatch at /doll/

And it concerns the HttpResponseRedirect(reverse('yourDollData', kwargs={'id': doll.id})) Tough, everything's fine with the doll.id which is printed out correctly one line before.

Of course when I hard access in my browser to 127.0.0.1:8000/yourdolldata/15/ it works perfectly. So it's all about this reversing process. I guess it has something to do with my url regex not matching what I think I'm reversing ...

How can i get that fixed ? I know it's a common mistake but I can't see any thing done the wrong way after I've done my internet research.


Solution

  • Add a name to the url attached to the view you are trying to reverse :

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

    Take the previous name as the argument of reversefunction .

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

    Reverse can take an url, a view name, or the name of a view attached to an url as first argument.