0
votes

What I want to do :

I am checking if user is from "support" group before he can view the page. If not I want to show proper message in response page to user. I have group_required decorator applied on dispatch() method of view that checks if user is from support group or not.

I have tried :

https://stackoverflow.com/a/29744943/2286762 but still getting the ValueError.

my code

view.py

class ScheduledTestView(FormView):
    '''
    Provides an admin panel interface for creating scheduled tests.
    Scheduled test will be created as active=False intially.
    '''
    serializer_class = TestShortSerializer
    template_name = 'admin/scheduled_test.html'
    form_class = ScheduledTestForm

    @method_decorator(group_required(['support']))
    def dispatch(self, request, *args, **kwargs):
        return super(ScheduledTestView, self).dispatch(request, *args, **kwargs)

group_required function

def group_required(group_names):
    """
     group_name will be the list of group name
    """
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            user = request.user
            if user.is_authenticated():
                if (user.groups.filter(name__in=group_names) and user.is_staff) or user.is_superuser:
                    return func(request, *args, **kwargs)
                return redirect_to_login('/admin/')
        return inner
    return decorator

Error

GET Request URL: http://localhost:8000/admin/support/scheduled_test/

Django Version: 1.8.4

Exception Type: ValueError

Exception Value:
The view support.views.ScheduledTestView didn't return an HttpResponse object. It returned None instead.

Exception Location: /home/kishan/.virtualenvs/kishan_pal/local/lib/python3.4/site-packages/django/core/handlers/base.py in get_response, line 151

1
What does inner return if the user is not authenticated?Daniel Roseman
That was the issue. Thanks for pointing out the mistake.Kishan Mehta

1 Answers

1
votes

As @Daniel Roseman mentioned in his comment below your question. If user is not authenticated then inner does not return any response whereas it should return redirect_to_login('/admin/') in that case.

So changing

def inner(request, *args, **kwargs):
    user = request.user
    if user.is_authenticated():
        if (user.groups.filter(name__in=group_names) and user.is_staff) or user.is_superuser:
            return func(request, *args, **kwargs)
        return redirect_to_login('/admin/')

to

def inner(request, *args, **kwargs):
    user = request.user
    if user.is_authenticated():
        if (user.groups.filter(name__in=group_names) and user.is_staff) or user.is_superuser:
            return func(request, *args, **kwargs)
    return redirect_to_login('/admin/')

should resolve the issue. See the difference return redirect_to_login('/admin/') is outside the if block.