R
R
R.2017-08-18 15:06:00
Django
R., 2017-08-18 15:06:00

Why does a redirect work in a "pure" form, but does not work from a function?

Perhaps this is a very simple, but not yet obvious thing for me. Why does this code work...

@login_required
def mem_area(request):
    """ Returns Member Area HTML with data """
    user = request.user

    if user.is_staff:
        return redirect('/')

    user_info = UserInfo.objects.get(user_id=user.id)
    page_title = 'Dashboard'
    return render(request, 'user_resume/member_area/member_area.html', locals())

and this one isn't? By "does not work" I mean that there is no redirect, and the admin gets to where it should not be.
def admin_redirect(user):
    """ Checks if user is admin and don't let him open member area  """
    if user.is_staff:
        return redirect('/')

@login_required
def mem_area(request):
    """ Returns Member Area HTML with data """
    user = request.user

    admin_redirect(user)

    user_info = UserInfo.objects.get(user_id=user.id)
    page_title = 'Dashboard'
    return render(request, 'user_resume/member_area/member_area.html', locals())

The only difference is that I moved the check "for admin" and the redirect to a separate function.
If I change return to raise Http404, then everything is ok, but I need a redirect

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artyom Belousov, 2017-08-18
@flygrounder

Because the redirect object is returned to the scope of your view, but the view itself does not return it.
The exception aborts all functions and returns 404

A
Astrohas, 2017-08-18
@Astrohas

def admin_redirect(user):
    """ Checks if user is admin and don't let him open member area  """
    if user.is_staff:
        return redirect('/')

@login_required
def mem_area(request):
    """ Returns Member Area HTML with data """
    user = request.user

    redirect = admin_redirect(user)
    if redirect:
      return redirect
    user_info = UserInfo.objects.get(user_id=user.id)
    page_title = 'Dashboard'
    return render(request, 'user_resume/member_area/member_area.html', locals())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question