【发布时间】:2017-04-20 16:26:55
【问题描述】:
我需要在几个视图中将一些上下文传递给模板。上下文是使用一些用户信息从 BD 获得的,所以我实现了一个特定的 ContextMixin 类:
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' 对象没有属性 '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。我的目标是重用将广告系列信息添加到上下文的代码。
谢谢
【问题讨论】:
标签: python django django-views