我正在閱讀有關模板視圖通過教程和一些代碼類型的困惑我。筆者使用此代碼示例模板視圖 - kwargs和** kwargs
from django.utils.timezone import now
class AboutUsView(TemplateView):
template_name = 'about_us.html'
def get_context_data(self, **kwargs):
context = super(AboutUsView, self).get_context_data(**kwargs)
if now().weekday() < 5 and 8 < now().hour < 18:
context['open'] = True
else:
context['open'] = False
return context
是困惑我語法是這樣的說法
context = super(AboutUsView, self).get_context_data(**kwargs)
如果我們已經收到**kwargs
那麼爲什麼我們把它傳遞給超級功能與**的事情(雙開始)。我想我們應該通過它作爲
context = super(AboutUsView, self).get_context_data(kwargs)
這是接收此調用的contextMixin。
class ContextMixin(object):
"""
A default context mixin that passes the keyword arguments received by
get_context_data as the template context.
"""
def get_context_data(self, **kwargs):
if 'view' not in kwargs:
kwargs['view'] = self
return kwargs
從我讀的是使用**kwargs
幾乎意味着kwargs是當前一本字典,需要轉換爲命名值。如果這是正確的,那麼當參數實際上是** kwargs時,kwargs如何成爲字典。我希望我的問題有道理。請讓我知道你是否想要我重述這個。
好吧,這絕對有道理。感謝您清除 –
順便說一句,你怎麼知道'def get_context_data(self,** kwargs):'實際上是接收字典中的kwargs? –
@JamesFranco看到我的編輯:大部分時間這是爲了接收未指定的關鍵字參數。 – brianpck