Reputation: 1027
I'm trying to get people on my site to access an entirely separate part of the site based on what user group they belong too. Here is the logic I've written so far:
if request.user:
if request.user.groups.filter(name='A').count() >= 1:
return HttpResponseRedirect('/pageA')
elif request.user.groups.filter(name='B').count() >= 1:
return HttpResponseRedirect('/pageB')
else:
return HttpResponseRedirect('/login')
And then urls:
url(r'', 'main.views.getIndex'),
url(r'', include('a.urls')),
url(r'', include('b.urls')),
So basically, I have group A & group B - user can access "A" page and "B" page accordingly if they belong to the respective user group. Otherwise, they have to login (placeholder denial page).
The logic seems to make sense, but I keep getting "too many redirects" error. In fact, the page actually gets to the statement I want it too but then upon returning HttpResponseRedirect, it stops working.
Your help is much appreciated.
Upvotes: 2
Views: 4445
Reputation: 2359
Well I don't know what code you have in a.urls
and b.urls
, but I will give you the way I almost always use when I should apply a redirect. It is only a new way you can have, of course. For example supposing you have this entry on a.urls
:
from django.conf.urls.defaults import *
urlpatterns = patterns('appA.views',
url(r'^pageA/$', 'pageA_view', name='pageA'),
)
you can apply this:
from django.shortcuts import redirect
# In your code
if request.user.groups.filter(name='A').count() >= 1:
return redirect('pageA')
It is another way you can accomplish this task. You can follow your idea too, but for a better understanding it would be useful to see what you have on your a.urls
and b.urls
.
Well, I just see the answer after I posted me response. Anyway, maybe it can help to someone.
Upvotes: 0
Reputation: 309089
The following pattern will match all urls
url(r'', 'main.views.getIndex'),
So if the getIndex
returns a redirect, you will get an infinite redirect loop.
If you only want the url pattern to match the index url (i.e. /
), then change it to:
url(r'^$', 'main.views.getIndex'),
The caret ^
matches the beginning of the string and the dollar $
matches the end of the string. Therefore ^$
only matches the empty string ''
. By contrast, the regex r''
matches all strings.
Upvotes: 5