A
A
Andrey Shubin2015-12-02 06:13:15
Django
Andrey Shubin, 2015-12-02 06:13:15

Access to different parts of the site by users from different groups?

I want to give users from different groups access only to their part of the site. I authorize like this:

def signin(request):
    if request.method == 'GET':
        return render(request, 'site/login.html')
    elif request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                if user.groups.filter(name__in=['Admins']) or user.is_superuser:
                    return HttpResponseRedirect('/cp/')
                elif user.groups.filter(name__in=['Counteragents']):
                    return HttpResponseRedirect('/counteragent/')
                elif user.groups.filter(name__in=['Clients']):
                    return HttpResponseRedirect('/client/')
            else:
                pass
        else:
            pass

Then, on the views, I check if the user belongs to the desired group:
def admin_check(user):
    if user.groups.filter(name__in=['Admins']) or user.is_superuser:
        return True
    else:
        return False

@user_passes_test(admin_check)
def admin_home(request):
    return render(request, 'admin/home.html')

Is there a better solution to this issue? Maybe this approach is not good at all?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2015-12-02
@idegree

Permissions

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question