Question

I'm having some trouble with the interaction between URLs and views. In my project, I have redirections and double redirections, and they are working fine, but when I try to recover the parameters captured by the regular expression the target view complains that it's receiving no parameters. This is my implementation:

project/urls.py:

lang_re = r'(ca|en|es|fr|ge)'

urlpatterns = patterns('',
    url(r'^$', RedirectView.as_view(url='/en/home/')),
    url(r'^'+lang_re+'/home/', include('components.home.urls', namespace='components.home')),
    ...
)

components/home/urls.py:

urlpatterns = patterns('',
    url(r'^$', RedirectView.as_view(url='cover')),
    url(r'^cover$', views.cover, name='home_cover'),
    ...
)

components/home/views.py

def cover(request, lang_code):
    ...

What happens here, for instance, when one goes to the root, is that one gets redirected to "/en/home". This matches the second regular expression (and it's supposed to capture the "en" part as a parameter), after which the user is redirected again to "/en/home/cover" through a relative redirection. This last URL finally finds a permanent view, "components.home.views.cover", and runs its function. The problem is that after the redirection the captured parameter ("en") seems to be lost, and Django gives me the following error message:

Request Method: GET
Request URL: http://localhost:8000/en/home/cover
Django Version: 1.5.2
Exception Type: TypeError
Exception Value: cover() missing 1 required positional argument: 'lang_code'

Any clue on how could I combine redirections and captured parameters?

Was it helpful?

Solution

You are facing that issue because in your regex, you do not have a named argument matching the view method.

Now to fix this issue:

lang_re = '(ca|en|es|fr|ge)'
url(r'^(?P<lang_code>'+lang_re+')/home/', include('components.home.urls', namespace='components.home')),

Read more on argument name matches of regex here

Note: You do not need the r'' around the regex.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top