问题
In my urlconf, i have:
url(r'^sssssh/(.*)', staff_only_app.site.root),
What I'd like to do is limiting any access to this application to superusers. I tried this:
url(r'^sssssh/(.*)', user_passes_test(staff_only_app.site.root, lambda u: u.is_superuser)),
But it complains that decorate takes exactly 1 argument, and I gave two.
I'm thinking about currying the decorator via functools.partial, but thought I may be missing some more obvious solution.
回答1:
Very late reply!...
I think it's just a quick and dirty syntax hangup:
url(r'^sssssh/(.*)', user_passes_test(lambda u: u.is_superuser)(staff_only_app.site.root),
^I think this is the strange but correct syntax for passing an argument to a decorator.
But on 2nd thought, you can only decorate view functions, not entire sites.
回答2:
Write a decorator similar to Django's login_required or f.ex. this one http://djangosnippets.org/snippets/254/ and decorate the view.
回答3:
Use the user_passes_test decorator.
example:
from django.contrib.auth.decorators import user_passes_test
@user_passes_test(lambda u: u.is_superuser)
def sample_view(request):
来源:https://stackoverflow.com/questions/3139284/django-limiting-url-access-to-superusers