django-tables2列标题,包含数据库中的值

时间:2015-04-17 17:30:50

标签: python django django-tables2

我正在尝试自定义django-tables2列的标头。最后,我希望我的桌子看起来像这样:

Date (timezone: US/Pacific) | value
 2015-Apr-05                |  10
 2015-May-03                |  20

我的模特:

class Event(models.Model):
  date = models.DateTimeField()
  value = models.IntegerField()
  user_profile = models.ForeignKey('UserProfile')

class UserProfile(models.Model):
  user = models.OneToOneField(User)
  timezone = models.CharField()

我的表:

class EventTable(tables.Table):
  class Meta:
    model = models.Event
    fields = ('date', 'value')

我的观点:

class SubscriberActivityView(View):
  def get(self, request):
    user_profile = UserProfile.objects.get(user=request.user)
    events = user_profile.event_set.all()
    context = {
      'event_table': EventTable(list(events))
    }
    # etc..

如何将UserProfile时区信息传递到表中?

1 个答案:

答案 0 :(得分:1)

您可以尝试这样:

表类:

class EventTable(tables.Table):
    def __init__(self, *args, date_verbose_name="",**kwargs):
        super().__init__(*args, **kwargs)
        self.base_columns['date'].verbose_name = date_verbose_name
    class Meta:
        model = models.Event
        fields = ('date', 'value')

查看:

class SubscriberActivityView(View):
  def get(self, request):
    user_profile = UserProfile.objects.get(user=request.user)
    date_verbose_name = user_profile.timezone
    events = user_profile.event_set.all()
    context = {
      'event_table': EventTable(list(events), date_verbose_name=date_verbose_name)
    }