Introduction to Django DateTimeField
As per Django, there are several field types through which the date and time values can be injected for storage on the models. The difference between these fields arises in the data’s format. There are options to store only date value; even time value alone can be captured. As per the datetime field, both date and time values will be captured. The user will be expected to place both the date and time values at the time of injecting the values for the storage. The stored value can again be retrieved back and displayed on the console.
Ex: 10-07-2019 00:20
Syntax:
Name_of_field = models.DateTimeField(**options)
The above syntax corresponds to the Django DateTimeField example. The first column mentioned here is the name of the field involved. The first column will form the field name, and next to it comes the models.DateTimeField extension. This extension means exporting the DateTime field method from the model’s section. So the model’s section will now import the DateTimeField method to generate the expected field. Next, you should specify the arguments for the DateTimeField() function in integer format. The usual values here are the null argument which mentions what needs to be the value for the records in which the valid date-time is not in place. The next argument will be the blank argument.
Create a Django DateTimeField
1. Changes in Models.py file:
As the syntax section mentions, the Date Time field must be declared in the models.py file. We can notice that the Date Time field is declared as the age field in the model.
(models.py)
from django.db import models
from django.contrib.auth.models import User
# Model variables
# Create your models here.
class Bride(models.Model):
DATE_TIME_name = models.CharField(max_length=200,null=True)
DATE_TIME_age = models.Date Time field_Example_Field(null=True)
DATE_TIME_DOB = models. DateTimeField (null=True)
DATE_TIME_thegai = models.CharField(max_length=200,null=True)
DATE_TIME_State = models.CharField(max_length=50,null=True)
DATE_TIME_District = models.CharField(max_length=50,null=True)
DATE_TIME_Address = models.TextField(null=True)
DATE_TIME_Phone = models.BigInteger(null=True)
DATE_TIME_profession = models.CharField(max_length=200,null=True)
DATE_TIME_salary = models.BigInteger(null=True)
DATE_TIME_Under_Graduation_Degree = models.CharField(max_length=200,null=True)
DATE_TIME_Under_Graduation_college = models.CharField(max_length=400,null=True)
DATE_TIME_Post_Graduation_Degree = models.CharField(max_length=200,null=True)
DATE_TIME_Post_Graduation_college = models.CharField(max_length=400,null=True)
DATE_TIME_Rasi = models.CharField(max_length=200,null=True)
DATE_TIME_Nakshatra = models.CharField(max_length=200,null=True)
def __str__(self):
return self.name
2. Changes in Settings.py file:
Ensure all of the values and the database connects are set nicely withinside the settings.py document in order that the venture may be kicked for execution flexibly. The middleware objects stated underneath need to be declared nicely withinside the settings.py document because those center wares are liable for the functioning of the software even as processing GET and PUT messages. Additionally, the templates used want to cram so that the template processing occurs within the background.
(Settings.py):
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Matrimony.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [Template_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'render_dict_processors': [
'django.template.render_dict_processors.debug',
'django.template.render_dict_processors.request',
'django.contrib.auth.render_dict_processors.auth',
'django.contrib.messages.render_dict_processors.messages',
],
},
},
]
3. Changes in url.py file:
The Media root and document root variables need to be instantiated inside the url.py file, like below. The changes for the url.py file are mentioned below.
url.py:
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from matrimony_pages import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$',views.Welcome_page,name='Welcome_page'),
url(r'Mainpage/',views.Main_page,name='Main_page'),
url(r'form/',views.form_view,name='form_view'),
url(r"signup/", views.Sign_up_request, name="register"),
url(r"login/", views.login_request, name="login"),
path(r'profile//',views.DATE_TIME_page,name='profile'),
url(r'logout/',views.logout_request,name='logout'),
url(r'reg/',views.DATE_TIME_reg_user,name='reg'),
path(r'update//',views.form_update,name='update'),
path('admin/', admin.site.urls),
]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
4. Create a view for the form:
Remember to store the value of the Date Time field after submitting and retrieve it from the database using the object of the model. Check out the views.py section below for step-by-step instructions on how to do this.
Ex: views.py
@login_required
def DATE_TIME_page(request,pk):
render_dict2 = {}
Key_details = Bride.objects.get(id=pk)
DATE_TIME_name = Key_details.name
DATE_TIME_Age = Key_details.age
DATE_TIME_DOB = Key_details.DOB
DATE_TIME_Thegai = Key_details.thegai
DATE_TIME_state = Key_details.State
DATE_TIME_district = Key_details.District
DATE_TIME_Address = Key_details.Address
DATE_TIME_Phone = Key_details.Phone
DATE_TIME_Profession = Key_details.profession
DATE_TIME_Salary = Key_details.salary
DATE_TIME_UG = Key_details.Under_Graduation_Degree
DATE_TIME_UGC = Key_details.Under_Graduation_college
DATE_TIME_PG = Key_details.Post_Graduation_Degree
DATE_TIME_PGC = Key_details.Post_Graduation_college
DATE_TIME_UG = Key_details.Under_Graduation_Degree
DATE_TIME_UGC = Key_details.Under_Graduation_college
DATE_TIME_PG = Key_details.Post_Graduation_Degree
DATE_TIME_PGC = Key_details.Post_Graduation_college
DATE_TIME_Rasi = Key_details.Rasi
DATE_TIME_Nakshatra = Key_details.Nakshatra
render_dict2['Age'] = DATE_TIME_Age
render_dict2['DOB'] = DATE_TIME_DOB
render_dict2['name'] = DATE_TIME_name
render_dict2['thegai'] = DATE_TIME_Thegai
render_dict2['State'] = DATE_TIME_state
render_dict2['district'] = DATE_TIME_district
render_dict2['Address'] = DATE_TIME_Address
render_dict2['Phone'] = DATE_TIME_Phone
render_dict2['profession'] = DATE_TIME_Profession
render_dict2['Under_Graduation_Degree'] = DATE_TIME_UG
render_dict2['Under_Graduation_college'] = DATE_TIME_UGC
render_dict2['Post_Graduation_Degree'] = DATE_TIME_PG
render_dict2['Post_Graduation_college'] = DATE_TIME_PGC
render_dict2['Rasi'] = DATE_TIME_Rasi
render_dict2['Nakshatra'] = DATE_TIME_Nakshatra
print(Key_details.Creator)
print(render_dict2)
return render(request,'Profilepage.html',render_dict2)
4) Formulate an HTML file for displaying the form: Corresponding changes to the HTML pages has to be performed.
Profilepage.html
<!DOCTYPE html>
<html style="font-size: 16px;">
<head>
<title>Profile</title>
{% load static %}
<link rel="stylesheet" href="{% static 'admin/css/Formpage.css' %}" media="screen">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" />
<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body class="body">
<nav class='navbar'>
<div class='navbar_div'>
<a class="navbar" onclick="redirect2()" >Home </a>
<a class="navbar" onclick="redirect2()" >Contact</a>
<a class="navbar" onclick="redirect1()" >Profiles</a>
</div>
</nav>
<div class="formarea">
<br>
{% block content %}
{% if Date Time field %}
<img src="{{Date Time field.url}}" align="right" alt="Date Time field" class="img-thumbnail" style="max-height:200px">
{% else %}
<img src="{% static 'admin/img/default.png' %}" align="right" alt="Date Time field" class="img-thumbnail" style="max-height:200px">
{% endif%}
<br></br>
<h6><strong>Name :    {{name}}</strong></h6>
<h6><strong>Age :    {{Age}}</strong></h6>
<h6><strong>DOB :    {{DOB}}</strong></h6>
<h6><strong>Thegai :    {{thegai}}</strong></h6>
<h6><strong>State :    {{State}}</strong></h6>
<h6><strong>district :    {{district}}</strong></h6>
<h6><strong>Address :    {{Address}}</strong></h6>
<h6><strong>Phone :    {{Phone}}</strong></h6>
<h6><strong>profession :    {{profession}}</strong></h6>
<h6><strong>Under Graduation Degree :    {{Under_Graduation_Degree}}</strong></h6>
<h6><strong>Post_Graduation_Degree :    {{Post_Graduation_Degree}}</strong></h6>
<h6><strong>Post_Graduation_college :    {{Post_Graduation_college}}</strong></h6>
<h6><strong>Rasi :    {{Rasi}}</strong></h6>
<h6><strong>Nakshatra :    {{Nakshatra}}</strong></h6>
{% endblock content %}
</div>
<script>
function form1() {
window.location.href = "http://127.0.0.1:8000/form";
}
function redirect1() {
window.location.href = "http://127.0.0.1:8000/Mainpage";
}
function redirect2() {
window.location.href = "http://127.0.0.1:8000/";
}
function redirect3() {
window.location.href = "http://127.0.0.1:8000/profile";
}
</script>
</body>
</html>
Output:
Conclusion
The above article displays the various details corresponding to the DateTimeField capability. This discussion covers how to use Datetimefield, the syntax of the field, the types of values it can store, and a practical example of how to select and store values. We also provide a reference image of the output from the example.
Recommended Articles
We hope that this EDUCBA information on “Django DateTimeField” was beneficial to you. You can view EDUCBA’s recommended articles for more information.