Formats

Internationalisation

Configurations

Récupèrer un texte i18n

On utilise django.utils.formats pour formatter des dates et nombres

Nombres

def get_imc(instance, field, data):
    return _('IMC : {}').format(
      formats.localize(data, use_l10n=True)
    )
separator = formats.get_format('NUMERIC_UNIT_SEPARATOR')

Dates

  today = datetime.date.today()
  now = datetime.datetime.now()

  # 2022
  print(formats.date_format(today, 'Y'))

  # 12/2022
  print(formats.date_format(today, 'SHORT_YEAR_MONTH_FORMAT'))

  # décembre 2022
  print(formats.date_format(today, 'FULL_MONTH_YEAR_FORMAT'))

  # déc 22
  print(formats.date_format(today, 'CONDENSED_MONTH_YEAR_FORMAT'))

  # 26/12/2022
  print(formats.date_format(today, 'NUMERIC_DATE_FORMAT'))

  # lundi 26 décembre 2022
  print(formats.date_format(today, 'l d F Y', use_l10n=False,))

  # 26/12/2022 24:59:59
  print(formats.date_format(now, 'NUMERIC_DATETIME_FORMAT'))

  # 24:59
  print(formats.date_format(now, 'TIME_FORMAT'))

  # 26 déc. 2022 24:59
  print(formats.date_format(now, 'SHORT_DATETIME_FORMAT'))

Formats date

Utilitaires

Taille du fichier (K,M,G)

from django.template.defaultfilters import filesizeformat

class File(models.Model):
    fileinput_size = models.PositiveIntegerField(
        editable=False,
    )

    @property
    def fileinput_size_formatted(self):
        return filesizeformat(self.fileinput_size)

Changer de locale