1

I'm trying to use user_pass_test in my URL's definitions for CBV and views.

I want to use a similar syntax to this:

url (r'^question_detail-(?P<pk>\w+)$', user_passes_test(not_in_group_chef,
login_url='public_connexion')Question_detail.as_view(), name='detail_question')

I found : Django - limiting url access to superusers and http://jonatkinson.co.uk/djangos-user_passes_test-and-generic-views/

But it's not functional in my case.

Thank you.

Community
  • 1
  • 1
Samuel Dauzon
  • 10,744
  • 13
  • 61
  • 94
  • possible duplicate of [django user\_passes\_test decorator](http://stackoverflow.com/questions/8082670/django-user-passes-test-decorator) See also: https://docs.djangoproject.com/en/dev/topics/class-based-views/intro/#decorating-class-based-views for an example of doing it in `urls.py`. – Peter DeGlopper Dec 23 '13 at 00:08
  • Thank you but the first link is for CBV on seperate file and the second show login_required and permission_required. Have a nice day – Samuel Dauzon Dec 23 '13 at 11:57

2 Answers2

2

you are missing a pair of brackets in your code example, does this work?

url (
    r'^question_detail-(?P<pk>\w+)$',
    user_passes_test(not_in_group_chef, login_url='public_connexion')(
        Question_detail.as_view()
    ),
    name='detail_question'
)
Anentropic
  • 32,188
  • 12
  • 99
  • 147
0

Anentropic was right, thank you !

For someone as the same problem:

The second problem that I solved is: for anonymous users, the not_in_group_chef function should verify if the user is registered. That way you won't get an error for anonymous users.

def not_in_group_chef(user):
if user:
    retour = False
    if User.objects.filter(username = user).count()==1:
        utilisateur = User.objects.get(username = user)
        if utilisateur.groups.filter(name='chef').count()==0:
            retour = True
        return retour
    return retour
return False
Tobias Roland
  • 1,182
  • 1
  • 13
  • 35
Samuel Dauzon
  • 10,744
  • 13
  • 61
  • 94
  • Django provides a simpler way to check for anonymous users without querying the db: `if user.is_anonymous()` https://docs.djangoproject.com/en/1.3/topics/auth/#django.contrib.auth.models.User.is_anonymous ...also your `not_in_group_chef` function should be receiving a User/AnonymousUser object, not a username string, so `User.objects.get(username = user)` shouldn't be needed – Anentropic Dec 23 '13 at 22:51