palewire

Who is Ben Welsh?

post  Django Recipe: Throw 404 errors on protected pages

Sometimes I extend the Django admin. It ain't nothing fancy. Typically, I just rack up bunch of extra pages, not meant for public consumption, where authorized users can turn over data and see what's what.

Django comes with a couple of handy tools for protecting a page. Both the @login_required and @staff_member_required decorators are exceptionally useful. However, both of them push unauthenticated users to your login box when they hit a private page.

This isn't that big of a deal, but it might be nice to send the outsider to a 404 page instead. In some cases, there's no reason they'd ever need to visit the page. And pushing to a login page they're never intended to use isn't going to help anything.

Here's a decorator I wrote to try and get that done.

from django.http import Http404
try:
    from functools import wraps
except ImportError:
    from django.utils.functional import wraps  # Python 2.3, 2.4 fallback.


def staff_member_or_404(view_func):
    """
    Decorator for views that checks whether the user is logged in
    and is a staff member. If they aren't, it throws a 404.
    
    This is a hack of the more sophisticated decorator found in:
    
        `django.contrib.admin.views.decorators`
    
    I'd like to use it in situations where I don't want a protected page to
    jump to the login screen.
    """
    def _checklogin(request, *args, **kwargs):
        if request.user.is_authenticated() and request.user.is_staff:
            # The user is valid. Continue to the admin page.
            return view_func(request, *args, **kwargs)
        else:
            raise Http404
            
    return wraps(view_func)(_checklogin)

And if you want to use it with your views, you can apply it in the same manner as Django's built in functions.

from toolbox.decorators import staff_member_or_404

@staff_member_or_404
def my_amazing_view(request):
    # All your fancy code here

Comments

arounsav on 2010.03.06
and I said to her, "all your fancy code here in a code haiku..." yeah.

Submit a comment

:
  Required
Email:
  Required
:
HTML allowed. Emails are not republished.

© 2008 palewire . colophon . los angeles time . cc 2.0 . powered by django