Joey Coder
Joey Coder

Reputation: 3489

Django: list index out of range

I have the following MultilingualQuerySet: super_guest = self.request.event.surveys.get_super_guests()

Out of this, I filter a variable that I return as a context variable. (There are several different context variables.)

context["reason_for_attending"] = list(filter(
    lambda question: question.focus == QuestionFocus.REASON_FOR_ATTENDING,
    super_guest
))[0]

Now it all works great as long there is an entry in the database. However, it can happen, that there are no "responses" yet. Then I get a list index out of range error. The reason is the [0]. Do you have a solution in mind?

Upvotes: 2

Views: 87

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

The reason this happens is because no item in super_guest matches the given condition (and super_guest might simply be empty as well).

You can use next(..) [python-doc] here, and pass a default value, for example:

context['reason_for_attending'] = next(filter(
    lambda question: question.focus == QuestionFocus.REASON_FOR_ATTENDING,
    super_guest
), None)

If there are no elements, then context['reason_for_attending'] will be None. You can then do some proper rendering in the template.

Upvotes: 1

Related Questions