Blocking a site in Django

I was recently a bit frustrated with my choices for locking down a site with Django so that nobody could see it. Well – that’s not tree, I wanted some people to be able to see it. Just not anyone…

After looking around a while, I spotted a solution that used Django Middleware to direct anyone who wasn’t logged in to a registration page. That provided the inspiration for a slightly different solution: I wanted to lock down the site to anyone (accounts or not) except for those folks who came through a beta signup process. I didn’t nessecarily want to “register” those folks with the site – and in fact, the first cut was simply “make them give me a password to get in” sort of thing.

The result was the following code:

First – the middleware:

from webcode.fuller.settings import ACCESS_COOKIE_NAME
from webcode.fuller.views import beta_auth, teaser

class BlockingMiddleware(object):
def process_request(self, request):
ident = request.session.get(ACCESS_COOKIE_NAME, None)
if ident is None:
if "sekret_access" in request.path:
return beta_auth(request)
return teaser(request)
return None

This layers on top of the session middleware that is provided with Django to drive the view "teaser" unless an access key is set in the session. In my case, I wanted the access limited to an obscure page not linked up from the teaser/splash page that would get presented.

The views:


def teaser(request):
""" just returns a bare-bones template render """
return render_to_response('fuller/teaser_block.html',
def beta_auth(request):
"""Displays a form template giving the user the option to provide the
'secret code' to get access to the site. This could be expanded a variety
of different ways, including checking against email, etc...     """
class BetaAuthManipulator(Manipulator):
"""A lightweight manipulator used for the sole purpose of working the
teaser/block setup. """
def __init__(self,request):
self.fields = (
manipulator = BetaAuthManipulator(request)
errors = {}
if request.POST:
new_data = request.POST.copy()
errors = manipulator.get_validation_errors(new_data)
if not errors:
if new_data['passcode'] == ACCESS_PASSCODE:
my_response = HttpResponseRedirect("/")
return my_response
return render_to_response('fuller/beta_auth.html',
{'form': formfields.FormWrapper(manipulator, request.POST, errors),},

And with this has a few new pieces in it:


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s