开发者

Is it possible to check whether a context variable is already set in a view within a custom context processor definition?

开发者 https://www.devze.com 2023-03-05 14:20 出处:网络
The issue is that in some views, I am manually getting a context variable (let\'s say \"G\") of interest since I use it to find other information in that particular view (i.e.views A,B,C), but in othe

The issue is that in some views, I am manually getting a context variable (let's say "G") of interest since I use it to find other information in that particular view (i.e.views A,B,C), but in other views (i.e. X,Y,Z), I need to get that particular context variable since this context is to be available in every single view in my project (since my base template uses the context variable). The issue with using a custom context processor is that I believe it will make an additional and IDENTICAL DB call in views (A,B,C) since those views are already getting that context variable since it's needed to get other data in the view. What I was thinking was maybe I could implement a context pro开发者_StackOverflow社区cessor that checks whether that specific context variable is set for a given request. Is this possible? Is there an easier solution? The code below may clarify the issue for some people.

Thank you 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)} 


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


I just made middleware that sets the variabel G to request.G since I need it on virtually every request anyway. 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're using direct_to_template, RequestContext, etc.).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号