[Answered ]-Django date format by an user

1👍

You were right that creating an entire database model just to represent a string is a pretty hardcore solution. Here are 2 alternative ways to do it:

1. Use a regular field and Django’s regex validator to validate that the input string only contains certain characters:

from django.core.validators import RegexValidator

class Formatter(models.Model):
    letters = models.CharField(max_length=6, validators=[RegexValidator(r"^[YyMmDd]{6}$")])

2. Don’t let users type their own format at all, and instead ask them which locale they would like to use for dates. You can activate a locale and get the list of its date formats like so:

>>> from django.utils.translation import activate
>>> from django.utils.formats import get_format
>>> activate('sv_SE') # locale for Sweden
>>> get_format('DATE_FORMAT')
'j F Y'

Leave a comment