Use Dot Notation to Build Django Contexts

Michael Shepanski
February 5, 2012
Feb
5

One thing about Django views that I personally find a bit annoying is using dictionary notation when building the context to pass to my templates. I don't find this a big deal for smaller views, but sometimes I have quite a bit of variables to pass back to my template. Organization, readability and maintainability often do not come in the syntactic form of a large dictionary of random objects.

I have been doing this for a few months now and thought I would share.

class AttrContext():
    """ Useful for dot notation context. """

    def __init__(self, **kwargs):
        self.update(kwargs)

    def __str__(self):
        return "\n".join(["%s: %s" % (k,v) for k,v in self.dict().iteritems()])

    def dict(self):
        rdict = {}
        for key, value in self.__dict__.iteritems():
            rdict[key] = value.dict() if isinstance(value, self.__class__) else value
        return rdict

    def update(self, data):
        for key, value in data.iteritems():
            setattr(self, key, value)

This generic little class makes it easier to simply add class variables to the object, and later convert this to a dictionary for Django goodness. The obligatory example usage is below. The variable vars is my context.

def summary(request, uuid):
    vars = AttrContext(request=request)
    vars.menuitem = 'accounts'
    vars.tabitem = 'summary'
    vars.baseurl = reverse('account', kwargs={'uuid':uuid})
    vars.account = get_object_or_404(Account, user_uuid=uuid)
    # Create and render the template
    template = "dashboard/account/summary.html"
    contextInstance = RequestContext(request)
    return render_to_response(template, vars.dict(), contextInstance)

Maybe it's useful for some others. :)


comments powered by Disqus