Class-Based Views – Am I Doing It Right?

I thought this would be simpler than it turned out to be. Here’s the ‘before’ code:

def start(request):
    ## clear out all session variables
    request.session['username'] = None
    
    return render_to_response('start.html',
                              context_instance=RequestContext(request) )

This view resets a session variable and sends out a template. Not too tough.

Next, is my first attempt to convert to a class-based view:

class StartView(TemplateView):
    template_name = "start.html"
    self.request.session['username'] = None

However, I quickly learned that ‘self’ is not available here. So, I picked a method, and overrode it to include my reset code:

class StartView(TemplateView):
    template_name = "start.html"
    
    def render_to_response(self,context, **response_kwargs):
        self.request.session['username'] = None
        return super(StartView, self).render_to_response(context, **response_kwargs)

Sure, this works, but there is likely a better way.

Please leave your suggestions in the comments below.

Comments are closed.