In this view, rather than raising a 404 if a piece of data is missing, I redirect back to a page where the user can specify the value.
def list_session(request):
event_id = request.session.get('event_id',None)
try:
event = Event.objects.get(pk=event_id)
except: #No event - back to staff page to select
return HttpResponseRedirect(reverse('staff'))
queryset = B2CSession.objects.filter(event = event)
params = {'queryset': queryset,
'paginate_by': DEFAULT_PAGINATION,
'template_name': 'session_list.html',
'extra_context': {'event': event,
'session': session}}
return object_list(request, **params)
I wanted to implement this same functionality using a class based view, so I looked into the available methods to override. The dispatch method was really the only choice. My solution:
def dispatch(self, request, *args, **kwargs):
## If there is no event_id set in the session, return to staff page for a chance to select one
try:
self.event = Event.objects.get(pk=request.session.get('event_id',None))
except Event.DoesNotExist:
return HttpResponseRedirect(reverse('staff'))
## Normal processing
return super(ListSessionView, self).dispatch(request, *args, **kwargs)
What do you think? Is this the best way to make this work? Leave your comments below.
