Home > Software design >  Modify how a field displays on Django tables2 table
Modify how a field displays on Django tables2 table

Time:04-12

I am trying to take a date field and display it in a django tables2 table. The issue is my field uses Djangos DateTimeField and has the time added on to the end which I don't care to display. My initial thought was to use a property decorator, and reference that in my table rather than using my original date field. But when I try to use split inside my property function nothing gets displayed in my table. If I modify the function to just print a string without using split it seems to work as intended. It seems that I can't use split anywhere in the function, even if I return a hard coded string instead of whatever I am splitting. Using split within the function just breaks it and makes it display nothing. Why can I not use split inside my function, and is there an alternative or better way of modifying what the date looks like when it displays on my table?

#tables.py
class ReportTable(tables.Table):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    class Meta:
        attrs = {"class": "mytable"}
        model = models.Report
        fields = ("formatted_date")
#models.py
class Report(models.Model):
    id = models.AutoField(db_column="RootCauseID", primary_key=True)
    date = models.DateTimeField(db_column="date", blank=False, null=True)

    @property
    def formatted_date(self):
        date = self.date
        date_list = date.split()
        final_date = date_list[0]
        return f"{final_date}"

    class Meta:
        managed = True
        db_table = "Report"

CodePudding user response:

You cannot split whatever is returned from the column because it is Python's datetime.datetime object. Documentation

class DateTimeField(auto_now=False, auto_now_add=False, **options)

A date and time, represented in Python by a datetime.datetime instance. Takes the same extra arguments as DateField.

And according to Marco, it seems like to can change the format of the datetime object yourself. Documentation

tables.DateTimeColumn(format ='M d Y, h:i A')
  • Related