Matt
Matt

Reputation: 4989

django-tables2 column header with value from database

I'm trying to customize the header of a django-tables2 column. Ultimately I'd like my table to look like this:

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

My models:

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

My table:

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

And my view:

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..

How do I pass the UserProfile timezone info into the table?

Upvotes: 0

Views: 1153

Answers (1)

ruddra
ruddra

Reputation: 52018

You can try like this:

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

View:

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

Upvotes: 2

Related Questions