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
This is a post Ben made on March 3, 2010, 6 days, 15 hours ago.
It is filed with other posts about car and web development.
Submit a comment