1

Let's say I have a model

class Job(Model):
     created_on = DateTimeField(_("Created On"), auto_now=True, editable=False)
     name = CharField(_("Name"), max_length=300, blank=False)

Now I am trying to aggregate all fields with their verbose name and value to display it in a template.

My aggregating function:

def get_fields(self):
    result = []
    for field in Job._meta.fields:
        result.append((field.name, field.verbose_name, field.value_to_string(self)))

This gives me the values as string properly, however for a datetime field, I end up with a dumb unformatted string like 2021-02-13T22:39:47.561045+00:00 I really don't want to check and modify the value in some way by specifically checking for the particular field as that is the whole point of my get_field function

I feel any of the following should work fine for me:

  1. Somehow provide the default format to use when calling value_to_string()
  2. Get a proper dateTime object instead, in which case the value should show up fine on the template
  3. Get field type and then instead of calling value_to_string() I manually convert the string to this type (This seems feasible from what I see but feels too hacky of a solution)
Dan Swain
  • 2,910
  • 1
  • 16
  • 36
L Lawliet
  • 2,565
  • 4
  • 26
  • 35

2 Answers2

1

@L Lawliet- Does something like this work. You can add it as models method.

def get_formatted_date(self):
        return self.created_on.strftime("%Y-%m-%d %H:%M:%S")

Alternative approach - source Formatting DateTimeField in Django

class CustomDateTimeField(models.DateTimeField):
    def value_to_string(self, obj):
        val = self.value_from_object(obj)
        if val:
            val.replace(microsecond=0)
            return val.isoformat()
        return ''

in your model

   created_on = CustomDateTimeField(auto_now_add=True)
SDRJ
  • 532
  • 3
  • 11
  • Well if I define it as a property, I can sort of get it to work but the problem is that if I do that, in my aggregation function, I have to make an exception specifically for that field which is what I am trying to avoid :( – L Lawliet Feb 14 '21 at 21:03
  • @LLawliet- I have made some edit. Can you try and see if that works? – SDRJ Feb 14 '21 at 21:07
  • Thanks. Apparently basic field.value_from_object(self) works for my case, but for getting a custom format by default, this seems ideal! – L Lawliet Feb 14 '21 at 21:12
1

Here is what worked for me:

field.value_from_object(self)

instead of

field.value_to_string(self)

The advantage is the return value is an object which is solution(2) for me. In this case since the object is of the proper type, it got displayed properly!

L Lawliet
  • 2,565
  • 4
  • 26
  • 35