django DateTimeField in form (initial value)

Question:

I have little problem with initial value of DateTimeField in Django forms.

I have declaration in forms.py

class FaultForm(forms.ModelForm):
    ...
    date_time = forms.DateTimeField(initial=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), required=False)
    ...

I have declaration in models.py

class Fault(models.Model):
    ...
    # date time
    date_time = models.DateTimeField(default=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    ...

Problem is with returning appropriate time.
When I add a few objects to my database with initial/default datetime from my forms.py I have exactly the same time for every object.

But when I add objects with datetime from template, I have good datetime for every object which is in database.

I have to tell my function to returning datetime is exactly the same in both of situation, but maybe problem is with generating the form?? We have the same time because we generate form once, or something like this??

I don’t know what to do with this, because I would like to use initial value from forms and don’t have to do it again in template.

Ony ideas?? Bug?? Other datetime function?? Other way to solve this little problem??

Please help me 🙂

Asked By: Grzegorz Redlicki

||

Answers:

You are calling the function datetime.now().strftime("%Y-%m-%d %H:%M:%S") and assigning the default as that. So, during runtime, the now() will get evaluated and stored as the default. Hence you see the same datetime across all your objects. You need to use the auto_now argument and set it to True.

Model –

class Fault(models.Model):
    ...
    date_time = models.DateTimeField(auto_now=True)
    ...
Answered By: shad0w_wa1k3r

Django model fields get evaluated at compile time. In your example above the default value gets evaluated once.

To fix this simple point the default argument to a callable:

def get_now():
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

class Fault(models.Model):
    date_time = models.DateTimeField(default=get_now)
Answered By: brianz

Use below Python method inside FaultForm class to initialize everytime the memory is allocated for the object:

def __init__(self, *args, **kwargs):
    kwargs.update( initial = { 'date_time': datetime.now() } )
    super( FaultForm, self ).__init__( *args, **kwargs )

[Explicit return in init][1]
[1]: https://docs.quantifiedcode.com/python-anti-patterns/correctness/explicit_return_in_init.html

Answered By: raul
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.