Django DateTimeField

Learn via video courses
Topics Covered

Overview

The date and time can be injected into various field types in Django to be stored on the models. The format of the recorded data determines how these fields differ from one another. There are possibilities for storing merely date values, or even only time values. Both the date and the time will be recorded in the DateTimeField. When injecting values for storage, the user will be required to enter both the date and time values. The cached value may once more be retrieved and shown on the console.

Introduction to Django DateTimeField

In Django, a date is represented by a datetime instance, and DateTimeField is a date and time field that stores its information. When using the Django ORM to define date-time-based database columns, DateTimeField is a frequently used attribute on Model classes. DateTimeField and all the other column fields are well-documented in the Django project. Django's datetime.datetime instance serves as the representative for the date and time field called DateTimeField. According to its name, a datetime object is stored in this field. For this field, TextInput is the default form widget.

Syntax

The Django DateTimeField example is consistent with the aforementioned syntax. The name of the relevant field is listed in the first column. The field name will be in the first column, followed by the models. To create the desired field, the model's section will now import the DateTimeField function. The DateTimeField() method's arguments must then be defined. The default values in this case are the null parameter, which specifies what should be the value for records where a valid date and time are missing. The blank argument will come up next.

Extra Optional Arguments

DateTimeField.auto_now

Every time the object is saved, set the field to now automatically. for "last-modified" timestamps, useful. It should be noted that the current date is never substituted; it is never used as a default value. Only when calling Model.save does the field get updated automatically. QuerySet.update(), for example, allows you to specify a custom value for the field; however, the field is not updated when other methods of updating other fields are used.

DateTimeField.auto_now_add

When the object is initially formed, it sets the field's value to now, which is helpful in timestamp creation. The current date will be used every time; it is not just any default value that can be changed. Therefore, even if a value was entered for this field when the object was created, it will not be used. Setting the following value in place of auto_now_add=True will allow you to edit this field:

  • For DateTimeField: default=datetime.now – from datetime.now()
  • For DateTimeField: default=timezone.now – from Django.utils.timezone.now()

Create a Django DateTimeField with an Example

1. Models.py Date Time field declaration in the models.py file is required, as mentioned below in the example code.

2. Changes in Settings.py file: Make sure that all of the settings are properly set up, including the values and the database connections.py document so that the project can be started for execution flexibly. The middleware items listed below must be properly specified inside the settings.py document, as those middlewares are in charge of the software's functionality when handling GET and PUT messages. For the template processing to take place in the background, the used templates also need to be compressed.

3. Changes in the url.py file: In the url.py file, the Media root and document root variables must be instantiated.

4. Create a view for the form: The Date Time field value must be stored when it is entered and must be retrieved from the database. This is possible with the help of the model-specific object. The views.py part that is provided below explains how to do this.

5. Create an HTML file for the form's display: It is necessary to make the necessary changes to the HTML pages.

How to use DateTimeField?

Django datetime.datetime instances are stored in the database using DateTimeField. Any kind of date and time can be stored in the database using the same method. Try storing a date in the previously generated model.

Field Options

When a field is given a constraint to apply or a characteristic to impart, these arguments are known as field options. To enable empty values to be stored for that table in a relational database, for instance, add the option null = True to DateTimeField.

Field OptionsDescription
NullIf True, Django will consider empty values in the database as NULL. False is the default setting.
BlankIf True, a blank value may be entered in the field. False is the default.
db_columna database column's name that will be used for this field. Django will use the field's name if this is omitted.
Defaultthe field's default value. This might be a callable object or a value. If it is callable, every time an object is created, it will be invoked.
help_textAdditional "help" text to appear alongside the form widget. Even if your field is not utilized on a form, it is still useful for documentation.
primary_keyIf True, this field serves as the model's primary key.
editableIf False, neither the admin form nor any other ModelForm will show the field. Additionally, they are not used for model validation. As a default, True.
error_messagesThe field will raise default messages that can be overridden using the error messages argument. You can override error messages by passing in a dictionary whose keys match the desired error messages.
verbose_namea field name that can be accessed by others. Django will automatically build the verbose name if it isn't provided, using the field's attribute name and converting underscores to spaces.
validatorsA validator is a callable that accepts a value and, if it doesn't satisfy certain requirements, raises a ValidationError. Validators can help share validation logic across many field types.
UniqueIf True, the table must contain only one instance of this field.

Conclusion

In the above tutorial, we saw

  • Various information about the DateTimeField capability as DateTimeField is a frequently used attribute on Model classes which represents datetime instance, and stores information of date and time.
  • The syntax is:
    Name_of_field = models.DateTimeField(options)
  • And a real-world example of selecting and storing the value is also covered.