Created
October 31, 2012 08:52
-
-
Save vdboor/3985939 to your computer and use it in GitHub Desktop.
Django view initialization ordering issues
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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