문제

I wrote a separate application for my Django site called restricted, and resides at

http://localhost:8000/restricted/

I want to be able to restrict access to this entire application to only members of a specific group (let's call it "Restricted Group").

Is there a way to easily do this? Perhaps in the urls.conf file? The app is full of class-based listviews (30+) so I'd hate to apply this kind of check to every single view in my view.py file.

EDIT: To fix this, I added a function to my view:

def group_check(user):
    if user:
        return user.groups.filter(name='Restricted').count() >= 1
    return False

For any normal view (such as index), I put the decorator:

@user_passes_test(group_check)
def index(request):
    return render_to_response('listview/index.html')

For my class-based listviews:

class MyListView1(ListView):
    context_object_name = "objs"
    queryset = MyList.objects.all()
    template_name = "listviews/mylist.html"

    @method_decorator(user_passes_test(group_check))
    def dispatch(self, *args, **kwargs):
        return super(MyListView1, self).dispatch(*args, **kwargs)

And for ones with a re-defined queryset:

class MyListView1_Custom(ListView):
    context_object_name = "obj"
    template_name = "listviews/mylist_custom.html"

    @method_decorator(user_passes_test(group_check))
    def get_queryset(self):
        self.obj1 = get_object_or_404(MyList, id__iexact=self.args[0])
        self.context = {}
        self.context['custom'] = self.obj1
        return self.context

Of course, this will require you to import:

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import user_passes_test

After testing, I concluded that this is a suitable method for protecting views based on groups. Any user who is not part of the group 'Restricted' is redirected to the default login page.

You can find more information at Django's documentation page: user_passes_test, which also describes how to redirect them to a different location (you can use this to redirect to a 404 if you'd like).

도움이 되었습니까?

해결책

In short - you can't do in urls conf. The reason is simple. Those files are compiled once Django starts and are not dynamically interpreted.

Instead you could build a custom decorator like restricted_required similar to login_required provided by django and use it everywhere you need.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top