﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
21626	Execute some common code before calling handler in Class Based Views	sahilkalra1991	nobody	"Hey,

I have had this problem now for sometime, there always come situations when '''I want to execute some common code (e.g. user access validation) before calling the handler''' (i.e. get/post/put) in Class based views

Currently I can do this in following 2 ways:
1. '''Create a method and call that separately in all handlers I support'''
     * Cons: This creates ''redundant code'' and doesn't look good

2. '''Over-ride dispatch() and execute common code before calling super class's dispatch()'''
     * Cons: This over-rides the default functionality of dispatch and executes the common code even for handlers I don't support as I am executing the common code before executing dispatch

'''I want to return 405 for handlers I do not support(default functionality) and execute some common code for handlers I support.'''

So, it would be really nice if we could have a generic way to do this, like following:
    
{{{
def dispatch(self, request, *args, **kwargs):
        # Try to dispatch to the right method; if a method doesn't exist,
        # defer to the error handler. Also defer to the error handler if the
        # request method isn't on the approved list.
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed

        validator_result = self.common_validator(request, *args, **kwargs) if getattr(self, 'common_validator', False) else None

        return handler(request, *args, **kwargs) if not validator_result else validator_result
}}}

So I can execute my common code like following:

{{{

def common_validator(request, *args, **kwargs):
    # my code
    # Return some result if not validated
    # or return None so that handler could be executed
}}}

Please provide your view on this. Is there any better way to do this ? Any help is appreciated.

Thanks "	Cleanup/optimization	closed	Generic views	dev	Normal	worksforme	generic views, class based views		Unreviewed	1	0	0	0	0	0
