[Solved] django how to format date to DD/MM/YYYY


A Model is not about how you present data to the customer, it is about how you store data in the database.

If you present data to the user, it depends on the settings that are active. If for example USE_L10N setting [Django-doc] is active, it will try to determine the locale of the user, and based on that format the date. This means that a German user will see a different date format than an American user for example.

If USE_L10N is set to False, the form field with use the first item in the DATE_INPUT_FORMATS setting [Django-doc]. By default this is:

[
    '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
    '%b %d %Y', '%b %d, %Y',            # 'Oct 25 2006', 'Oct 25, 2006'
    '%d %b %Y', '%d %b, %Y',            # '25 Oct 2006', '25 Oct, 2006'
    '%B %d %Y', '%B %d, %Y',            # 'October 25 2006', 'October 25, 2006'
    '%d %B %Y', '%d %B, %Y',            # '25 October 2006', '25 October, 2006' ]

so it will first format the year, month and then date, so 2020-08-28 for example. You thus can specify a different element (first) to change this for all Forms that have DateField fields [Django-doc].

If you want to specify a one-off field, you can use the format=… parameter [Django-doc] of the DateInput widget for example:

from django import forms

class InvoiceForm(ModelForm):
    date = forms.DateField(widget=forms.DateInput(format="%d/%m%Y"))

    class Meta:
        model = Invoice
        fields="__all__"

Then you should also include the format in the DATE_INPUT_FORMATS setting, and better with a higher priority than “overlapping” formats like %m/%d/%Y and %m/%d/%y, to ensure that the value can also be parsed.

You can also provide a one-off list of input formats in the form field by specifying a input_formats=… parameter [Django-doc]

3

solved django how to format date to DD/MM/YYYY