django-tables2 列 header 具有来自数据库的值

django-tables2 column header with value from database

我正在尝试自定义 django-tables2 列的 header。最终我希望我的 table 看起来像这样:

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()

我的table:

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 时区信息传递到 table?

你可以这样试试:

Table Class:

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)
    }