Search code examples
djangodjango-tables2

How do I customise the display text of a related object in a column in Django Tables2?


I'm using Django Tables 2 to display some information from a list of objects, including a column with a related object. I'm trying to change the text displayed in the column that shows the related object.

My objects are:

Job

class Job(StatusModel):
    '''
    Model for jobs
    '''

    STATUS = statuses.JOB_STATUS

    start_time = models.DateTimeField(_('time'), default=timezone.now)
    pickup_address = models.TextField()
    ...
    destination_address = models.TextField()
    ...
    drivers = models.ManyToManyField(
        'Drivers.Driver',
        blank=True,
    )
    ...

    class Meta:
        verbose_name = _('job')
        verbose_name_plural = _('jobs')
        ordering = ('start_time',)

    def __str__(self):
        return self.start_time.strftime('%d/%m/%y %H:%M') + ' from ' + self.pickup_address

    def get_absolute_url(self):
        return reverse('job_view', args=[str(self.id)])

    ...

Driver

class Driver(StatusModel):

   ...
    current_job = models.ForeignKey(
        Job,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        verbose_name=_('Current Job'),
        related_name='current_job'
    )
    ...
    def __str__(self):
        return self.user.get_full_name()

    ...

My table:

class DriverStatusListTable(tables.Table):

    user = tables.Column(linkify=True, verbose_name=_('Driver'))
...
    current_job = tables.Column(linkify=True)

    class Meta:
        model = Driver
...

I want the "current_job" column to show text different to the returned __str__ representation of the Job object - namely: Job.start_time.strftime('%H:%M') + ' to ' + Job.destination_address, but I can't work out how to do this, without changing the __str__ method on the Job object.

Any ideas?


Solution

  • Write a Table.render_foo to customize the value output.

    Example:

    
    class DriverStatusListTable(tables.Table):
        user = tables.Column(linkify=True, verbose_name=_('Driver'))
        current_job = tables.Column(linkify=True)
    
        class Meta:
            model = Driver
    
        def render_current_job(self, value):
            return "Use 'value' parameter here and return useful resposne"