[Answer]-Appending render with decorator in Django

1👍

You could do one of the following. First, you could change the definition of your listall view function to

def listall(request, unreadcount=None):

That way unreadcount will be in the context of the listall function and you can call render as you have written above. Alternatively, you could change your render line to

return render(request, 'static/list.html', {'loggedin': True, 'unreadcount': kwargs['unreadcount']})

Either way, it looks like your decorator could use some simplification. All it needs to do is ensure that unreadcount is in the kwargs for the view that it’s decorating, and to set it’s value. The following should work with either of the above corrections.

def countreademail(view):
    def wrapper(request, *args, **kwargs):
        exists, myid = myexists(request)
        kwargs['unreadcount'] = messagescount(myid)[0]
    return view(request, *args, **kwargs)
return wrapper

That being said, it’s possible that you should consider using a non-decorator solution, since all you’re using it for is adding single variable to the context of the view function and calculating a value for it. You could use the following, simpler solution instead.

def countunreademail(request):
    exists, myid = myexists(request)
    return messagescount(myid)[0]

def listall(request, *args, **kwargs):
    unreadcount = countunreademail(request)
    return render(request, 'static/list.html', {'loggedin': True, 'unreadcount': unreadcount })
👤stett

Leave a comment