Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django 'url' template tag error

My URLconf contains this pattern:

url(r'^accounts/logout/$','django.contrib.auth.views.logout', name="logout"),

And I've trying to reverse that in a template with the URL tag like this:

<a href="{% url logout next_page=request.path %}">logout</a>

But I keep getting the following error:

Reverse for 'logout' with arguments '()' and keyword arguments '{'next_page': u'/first-page/child/'}' not found

I thought django.contrib.auth.views.logout is supposed to take an option next_page parameter. I'm sure I'm missing something obvious, but I'm not sure what it is.

like image 499
saturdayplace Avatar asked Feb 04 '23 09:02

saturdayplace


2 Answers

Yes you're right, django.contrib.auth.views.logout does accept an optional "next_page" parameter, but don't forget that the "url" tag matches to urlconf patterns, not views, so it's not aware of what is or isn't a parameter of a view. So this suggests that you need to make "next_page" a named group in the regexp for the above pattern, which you could do, but there's an easier way to handle redirects...

Looking at django.contrib.auth.views.logout, you can see that in the absence of a "next_page" parameter, the view redirects to whatever url is provided in either request.GET or request.POST with the key "redirect_field_name", a parameter which defaults to "REDIRECT_FIELD_NAME" which in turn defaults to the string "next". So leaving your urlconf the way it is, you can do something like this in your template:

<a href='{% url logout %}?next={{ request.path }}'>logout</a>
like image 98
ozan Avatar answered Feb 08 '23 16:02

ozan


Basically Django's URL dispatcher is looking at the urlconf and that argument and saying "I don't know where to put this argument" because it doesn't look at the view functions the urls point to, only the urlconf and the patterns in it.

Right now there's no place in your url pattern for that argument.

i.e. you can call django.contrib.auth.views.logout with the extra arguments if you write your own pattern for it or if you call it from your own view, but not from its default url pattern.

One of these url patterns might work for you (not tested):

url(r'^accounts/logout/(?P<next_page>.*)?$','django.contrib.auth.views.logout', name="logout"),
url(r'^accounts/logout/$','django.contrib.auth.views.logout', kwargs={'next_page':None}, name="logout"),

Hope that helps!

like image 38
Gabriel Hurley Avatar answered Feb 08 '23 17:02

Gabriel Hurley