Django: how to move the "page not found" exception and context from function to class-based view?
I'm converting a simple function to a class-based view. I had found a good resource with examples that helped me in the past to better understand the whole topic (can be found here), but I couldn't find a good example of how to handle exceptions related to a page in a class-based view when the page is not found (for example, someone makes a typo in URL).
I'm also not sure how to handle additional context that I want also transfer to class-based view.
I would appreciate some help, and suggestions based on this simple example below. My goal is to import the main View
with `from django.views import View' and place all logic in this class instead of this function.
def meetup_details(request, meetup_slug):
try:
selected_meetup = Meetup.objects.get(slug=meetup_slug)
return render(request, 'meetups/meetup-details.html', {
'meetup_found': True,
'meetup_title': selected_meetup.title,
'meetup_description': selected_meetup.description
})
except Exception as exc:
return render(request, 'meetups/meetup-details.html', {
'meetup_found': False
})
class MeetupDetailView(DetailView):
model = Meetup
template_name = "meetups/meetup-details.html"
queryset = Meetup.objects.all()
def get_object(self):
try:
self.meetup = Meetup.objects.get(slug=self.kwargs['slug'])
except Exception as exc:
self.meetup = None
return self.meetup
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if self.meetup:
meetup_found = True
context['meetup_title'] = self.meetup.title
context['meetup_description'] = self.meetup.description
else:
meetup_found = False
context['meetup_found'] = meetup_found
return context