Answer the question
In order to leave comments, you need to log in
How to correctly pass the context to the Django view if the context object may not have been created?
I have groups, the user can enter the group. When he views the page of the group, if he has already joined it, I need to display information about him. It works for me like this:
class UniverseDetailView(LoggedInMixin, DetailView):
model = Universe
template_name = 'multiuniverse/universe_detail.html'
def get_context_data(self, **kwargs):
context = super(UniverseDetailView, self).get_context_data(**kwargs)
member = Member.objects.get(user=self.request.user, uni=self.object)
context['member'] = member
return context
Exception Type: DoesNotExist
Exception Value: Member matching query does not exist.
Answer the question
In order to leave comments, you need to log in
We helped to figure it out, we write a function to handle an exception (DRY):
def get_or_none(model, **kwargs):
try:
return model.objects.get(**kwargs)
except model.DoesNotExist:
return None
member=get_or_none(Member, user=self.request.user, uni=self.object)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question