C
C
Cyril2014-05-13 04:29:03
Django
Cyril, 2014-05-13 04:29:03

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

But, if he did not join the group before viewing, which is quite logical, an error is thrown:
Exception Type: DoesNotExist
Exception Value: Member matching query does not exist.

How can this context be passed without resorting to get_or_create? Because I do not want to produce a bunch of unnecessary records.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Cyril, 2014-05-13
@aeHarkonnen

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

And use it instead:
put:
member=get_or_none(Member, user=self.request.user, uni=self.object)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question