3👍
There are two problems here:
- the
DateField(default=today.today())
will not work, since then the function will be evaluated eagerly, and then the default value is thus the result of that function call. As a result the default value is not calculated when constructing a new object, and hence eventually will be different; and - the representation of a
DateField
. Now the model layer does not specify a representation, it only specifies how to store values in the database, and defines functions on a model.
We can solve the first problem by passing a reference to the today
function, like:
from datetime import date
class A(models.Model):
date = models.DateField(default=date.today) # no ()
As for the representation, you should specify the format in the template, for example with the date
template filter [Django-doc], like:
<!-- template.html -->
{{ some_a.date|date:'d-m-Y' }}
Or in a form with:
# app/forms.py
class AForm(ModelForm):
date = DateField(input_formats=['%d-%m-%Y'])
class Meta:
model = A
1👍
You can use the DATE_INPUT_FORMATS setting in your Django project settings, this will allow you to make date.today().strftime('%d-%m-%Y')
be accepted by your model field; however, the DateField is stored in your database as the native column of the same type and not as a string with a specific format. There is a difference between storing the data and representing it in your forms, templates or DRF serializers. I really recommend keeping the default format for the database and present the data in the format you want by using the DATE_FORMAT setting to d-m-Y that will take care of presenting your dates in that format as long as the USE_L10N setting is False.
- [Django]-Elastix API for communicating with django web application
- [Django]-Model Many to Many relations with Abstract Class
- [Django]-Django queries: Count number of objects with FK to model instance
0👍
if you want to use the same format for display and input, you have to specify input_formats and format(in widget) respectively. for example
class OrderForm(forms.ModelForm):
deadline = forms.DateTimeField(
input_formats=['%d/%m/%Y %I:%M %p', ], # input format
widget=forms.DateTimeInput(format="%d/%m/%Y %I:%M %p"), # initial display format
)