Skip to content

Instantly share code, notes, and snippets.

@vdboor
Created October 31, 2012 08:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vdboor/3985939 to your computer and use it in GitHub Desktop.
Save vdboor/3985939 to your computer and use it in GitHub Desktop.
Django view initialization ordering issues
class BaseViewMixin(object):
def dispatch(self, request, *args, **kwargs):
# Set earlier to let get_loggedin_user() and get_context_user() work.
# They run before the get() and post() methods are called.
self.request = request
self.args = args
self.kwargs = kwargs
# Run checks before entering the view.
# Note that is_authorized() does not have access to self.object yet,
# as the normal get() and post() methods are not entered.
if not self.is_authorized():
html = render_to_string("403.html", {}, context_instance=RequestContext(request))
return HttpResponseForbidden(html)
# Give all subclasses a chance to fetch database values that depend on the context user,
# before entering the global get/post code that does everything. In contrast to overriding get/post, the init()
# function can call super() first, to let the parent class initialize, and then initialize itself.
# A get/post function can't run super first, since that would execute the whole view.
self.init()
# Run the complete request, returning a response
return super(PermissionMixin, self).dispatch(request, *args, **kwargs)
def init(self):
# Hook to override in subclasses
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment