Reputation: 336
I need to display the form in a different format => "%d%m%Y". I tried everything but nothing works.
In my forms.py
class DateInput(forms.DateInput):
input_type = 'date'
class VendaForm(forms.ModelForm):
class Meta():
model = Venda
exclude = ['acertado', 'status', 'viagem', 'paid',]
widgets = {
'sale_date': DateInput(),
'expiration_date': DateInput(),
}
Upvotes: 2
Views: 12922
Reputation: 21822
To customize the format a DateField
in a form uses we can set the input_formats
kwarg [Django docs] on the field which is a list of formats that would be used to parse the date input from the user and set the format
kwarg [Django docs] on the widget which is the format the initial value for the field is displayed in.
If we don't provide these arguments the formats used are from the DATE_INPUT_FORMATS
setting [Django docs] (for the widget the first format in this list is used) so we can also change this setting if we want it for all date fields in our project.
To set the format for the field specifically your code would be like:
class VendaForm(forms.ModelForm):
sale_date = forms.DateField(
widget=forms.DateInput(format='%d%m%Y'),
input_formats=['%d%m%Y']
) # Perhaps you should consider a separator in this format i.e. `%d-%m-%Y` instead of `%d%m%Y`
expiration_date = forms.DateField(
widget=forms.DateInput(format='%d%m%Y'),
input_formats=['%d%m%Y']
)
class Meta():
model = Venda
exclude = ['acertado', 'status', 'viagem', 'paid',]
Upvotes: 6
Reputation: 2435
you can do this {{ date_field | date:"d-m-Y" }}
# Output will be for example 14-05-2021
also if u want to change your date format from db check out this link.
Django docs for date templatetag
Upvotes: 1
Reputation: 2165
you could add in your template
{{date_field_name|date:'%d-%m-%Y'}} # change date_field_name to the name of your field
Upvotes: 1