Question

I'm using render with the following:

@countunreadmail
def listall(request, *args, **kwargs):

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

but I want to append the render line to include some additional kwp's that are computed in a decorator that is used before the function. So the dectorator function is for example:

def countunreadmail(view):
    def wrapper(request, *args, **kwargs):
        exists, myid = myexists(request)
        unreadcount = messagescount(myid)[0]            
        r.context_data = {'unreadcount': unreadcount}
        context = {'unreadcount': unreadcount}
        kwargs = dict(kwargs.items() + context.items())
        return view(request, *args, **kwargs)
    return wrapper

so how can I add get the following in the render line:

return render(request, 'static/list.html', {'loggedin': True, 'unreadcount': unreadcount})
Was it helpful?

Solution

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 })
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top