2010-08-19 41 views
2

我寫了一個包裝圍繞render_to_response看起來像這樣爲什麼添加這些常量到我的模板變量讓我登錄?

from app import constants 

def response(request, template, vars={}): 
    if '.' not in template: 
     template += '.html' 
    template_vars = {} 

    for constant in dir(constants): 
     if constant[:2] == '__': continue 
     template_vars[constant] = getattr(constants, constant) # BUG: causes you to stay logged in 
    template_vars.update({'settings':settings}) 
    template_vars.update({'request':request}) 
    template_vars.update(vars) 

    return render_to_response(template, template_vars, context_instance=RequestContext(request)) 

看來,通過添加常數到模板增值經銷商,user.is_authenticated總是在模板返回true,user.username一些隨機用戶獲取其值(最最近登記了什麼)。只是想知道這是爲什麼?

有人在乎解釋嗎?

如果我打印的常數,這些都是他們

BidReasons 
BidStatuses 
CA_PROVINCES 
COUNTRIES 
CancellationRequestStatuses 
EMAIL_NOTIFICATIONS 
Enum 
Flags 
InvoiceStatuses 
NA_REGIONS 
PaymentMethods 
PaymentTimes 
PaymentTypes 
SELECT_OPTION 
SecretKeyPurposes 
Sequence 
ServiceTypes 
ShipmentStatuses 
USER_RATINGS 
US_STATES 
VehicleListingOptions 
WeekDays 
YES_OR_NO 

我沒有看到任何東西在裏面那會惹user


我的新修補程序,如果好奇:

def response(request, template, vars={}): 
    if '.' not in template: 
     template += '.html' 

    template_vars = {'settings':settings, 'request':request, 'constants':constants.__dict__} 
    template_vars.update(vars) 

    return render_to_response(template, template_vars, context_instance=RequestContext(request)) 
+0

爲什麼你將常量.__ dict__分配給template_vars,更新它兩次,然後將它重新分配給變量?我不認爲這是造成問題,它只是脫穎而出。 – 2010-08-19 02:26:33

+0

你是如何使用這個功能的?這聽起來像它可能是一個線程安全的問題,就像你傳遞了一個不同的請求到模板中並覆蓋RequestContext中的「請求」。 – 2010-08-19 02:31:08

+0

@Matthew:糟糕......當我試圖弄清楚什麼是錯誤的時候,這是殘留物:p我在幾乎每個視圖函數的末尾都使用它來代替'render_to_response'。 – mpen 2010-08-19 05:28:55

回答

1

與你的問題沒有真正的關係,但是如果你想添加變量到你的模板co ntext,而不是在每個視圖中調用一個單獨的函數,您可能需要查看自動執行相同操作的context processors

+0

Hrm ...沒有想到這一點。好建議!儘管如此,我仍然想擺脫那個討厭的'context_instance = RequestContext(request)'位。它過去也使用基於視圖func名稱的默認模板...但是沒有完成。 – mpen 2010-08-19 16:32:12

相關問題