Can I check if a context variable has already been set in a view in a user context processor definition?

The problem is that in some views I get a context variable (say, “G”) because I use it to search for other information in this particular view (ie, view A, B, C), but in other views (i.e., X, Y, Z) I need to get this particular context variable, because this context should be available in every single view in my project (since the context template is used in the base template). The problem with using a custom context handler is that I believe that it will make an additional and IDENTICAL DB call in the views (A, B, C), since these views already receive this context variable, since it takes to get other data in the view . What I was thinking about, maybe I can implement a context processor,which checks if this particular context variable is set for a given request. Is it possible? Is there an easier solution? The code below may clarify the issue for some people.

Thanks for any advice!

def viewA(request):
    g=G.objects.get(user=request.user)
    posts = Post.objects.filter(g=g)
    return direct_to_template(request,'something.html',{'G':g, 'posts':posts})

def viewX(request):
    stuff = Albums.objects.get(user=request.user)
    return direct_to_template(request,'something2.html',{'stuff':stuff})

def my_context_processor(request): #redundant in case of viewA (hits db again?)
    return {'G':G.objects.get(user=request.user)} 

def ideal_processor(request):
    #check context vars to see if G is already in there
    #if it is, return {}, else, return {'G':G.objects.get(user=request.user)} 
+3
source share
2 answers

I just made a middleware that sets the G variable for the .G request, since I need it on almost every request. i.e:.

class GuildMiddleware(object):
    def process_request(self, request):
        request.G = figure_out_what_G_is()
        return None

Now you can use request.G anywhere in your views (and templates if you use direct_to_template, RequestContext, etc.).

0
source
def always_G(request):
    if not hasattr(request, 'G'):
        {'G':G.objects.get(user=request.user)}
0
source

All Articles