Callum
Callum

Reputation: 1165

Django other_dict Error

I get the latest 5 messages and events the user has received for the authenticated users with a context processor and this is what i'm using:

def notifications(request):
    # only authenticated users will have notifications
    if request.user.is_authenticated():
        events = Event.objects.filter(user_to=request.user).order_by('-time_sent')[:5]
        mails = Message.objects.filter(user_to=request.user).order_by('-sent')[:5]
        # return the two resultsets to the template
        return {
            'notification_events': events,
            'notification_mails': mails
        }

If the user is logged in it works great, but when I logout I get this error:

other_dict must be a mapping (dictionary-like) object

At first I thought it was because of the return but it works when the user is authenticated so its possibly an issue with request.user.is_authenticated()

Upvotes: 0

Views: 71

Answers (1)

felipsmartins
felipsmartins

Reputation: 13549

you should default return (fallback dict) when the boolean expression is not satisfied, something like:

if request.user.is_authenticated():
    ...
    return {
        'notification_events': events,
        'notification_mails': mails
    }
else:
    #fallback
    return {
        'notification_events': None,
        'notification_mails': None
    }

Upvotes: 1

Related Questions