3
我需要傳遞一些上下文到模板的幾個視圖。上下文從BD使用一些用戶的信息獲取,所以我已經實現了一個具體ContextMixin類:Django ContextMixin'超級'對象沒有屬性'get_context_data'
class CampaignContextMixin(ContextMixin):
"""
This mixin returns context with info related to user's campaign.
It can be used in any view that needs campaign-related info to a template.
"""
def get_campaigns(self):
# Get the first campaign related to user, can be more in the future
return self.request.user.campaign_set.all()
# Method Overwritten to pass campaign data to template context
def get_context_data(self, **kwargs):
context = super(CampaignContextMixin).get_context_data(**kwargs)
campaign = self.get_campaigns()[0]
context['campaign_name'] = campaign.name
context['campaign_start_date'] = campaign.start_date
context['campaign_end_date'] = campaign.end_date
context['org_name'] = self.request.user.organization.name
context['campaign_image'] = campaign.image.url
context['campaign_details'] = campaign.details
return context
然後,我想在我的觀點中使用它,但我發現了一個錯誤:
'super' object has no attribute 'get_context_data'
class VoucherExchangeView(CampaignContextMixin, TemplateView):
"""
This view Handles the exchange of vouchers.
"""
template_name = "voucher_exchange.html"
def get_context_data(self, **kwargs):
ctx = super(VoucherExchangeView).get_context_data(**kwargs)
# add specific stuff if needed
return ctx
我不知道是否是因爲導致錯誤的繼承,還是因爲TemplateView從ContextMixin也繼承。我的目標是重用將廣告系列信息添加到上下文中的代碼。
感謝
謝謝!那是問題,我忘了通過自我! –