django DateTimeField in form (initial value)

django form initial value
django form fields
django forms
django datefield format
django form widgets
django form validation
django form widgets example
django form field value

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 :)

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)
    ...

Form fields | Django documentation, forms.DateField, initial doesn't print out in input_formats format With what you specify, the initial date value as displayed on the form will not from django import forms >>> from datetime import date, timedelta >>> class DF(forms.Form): � So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True: For DateTimeField: default=datetime.now – from datetime.now() For DateTimeField: default=timezone.now – from django.utils.timezone.now()

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)

11231 (forms.DateField, initial doesn't print out in input_formats format), initial -- A value to use in this Field's initial display. This value # is *not* def strptime(self, value, format): return datetime.datetime.strptime(value, format).date (). Django form DateTimeField initial value is blank. Ask Question Asked 3 years, 5 months ago. Active 3 years, 5 months ago. Viewed 394 times 0. I have a create form in

Use bellow 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

django.forms.fields | Django documentation, 09-10-2019. DateField is a field which stores date, represented in Python by a The default form widget for this field is a TextInput . Note that the current date is always used; it's not just a default value that you can override. DateField in Django Forms is a date field, for taking input of dates from user. The key part of the implementation is to assure Django will receive the date input value in the correct format, and also that Django will be able to reproduce the format when rendering a form with initial data.

DateField - Django Models, Form fields. In this case, we have a single DateField for entering the renewal date that will render in HTML with a blank value, the default� If I add a DateTimeField to the form's localized_fields Meta property (in order to get the date correctly formatted), then the rendered field value is no longer converted to the activated timezone. by ctrl-alt-delete @ ctrl-alt-. The Django ORM is very powerful. conversion of datetime Field to string in django queryset.

Django Tutorial Part 9: Working with forms, Let's explore how we could make use of them in Django forms. the model form with some initial values, then print the form as HTML to the console, datetime import datetime, date, time >>> form = ExhibitionForm(initial={ . The initial argument lets you specify the initial value to use when rendering this Field in an unbound Form. To specify dynamic initial data, see the Form.initial parameter. The use-case for this is when you want to display an “empty” form in which a field is initialized to a particular value.

Working with Dates and Times in the Forms, How to set initial values on Djang forms, how to extract values from Django forms, also applies to other form fields with non-string data types (e.g. DateField() ). You have two options either populate the value when calling form constructor: form = JournalForm(initial= {'tank': 123}) or set the value in the form definition: tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) share. Share a link to this answer. Copy link.

Comments
  • in this solution I have such error: django.core.exceptions.FieldError: 'date_time' cannot be specified for Fault model form as it is a non-editable field I try to disable this field but it is not working anyway
  • If you want the field to be editable, then remove the auto_now=True part in the Model form.
  • So your answer is useless. You tell me that I need to use auto_now argument to solve my problem but when this argument give me another problem you tell me that I have to remove auto_now?? How can it help me??
  • You did not give the specifics in the question. Anyway, auto_now will always add the datetime, and would be render the field as uneditable. You have to choose between adding it automatically or using an editable field, for which you are providing an initial. Plain & simple, you just have to remove the auto_now from the Model field and keep the initial in the Form field, like my answer+comment says. And my answer is not "useless" because I also pointed out the "why" your solution is not working.
  • I told it because you told add "auto_now" and after testing you told remove "auto_now", so I was in the same place so before your answer. Anyway I read something about "auto_now" and how to use it and everything is good now after little changes, so I will plus this answer
  • Although this may work, one should prefer the built-in auto_now.
  • Perhaps, but it depends on the situation and in this question there isn't enough information to reliably suggest that.
  • Exactly, since there is not enough information, one should always prefer the built-in.
  • good solution but not working as I want, I have the same time for two object added one after another What exactly do you want to know??