Are you tired of using boring and outdated form inputs for dates on your Django website? Look no further! In this blog post, we will show you how to add a sleek and modern date input widget to your Django forms. With just a few simple steps, you can add the date input widget to your Django forms. Let's get started!
I am showing you an example of Student Profile. So let's create a simple StudentProfile model.
# models.py
from django.db import models
class StudentProfile(models.Model):
student_first_name = models.CharField(
'Student First Name',
max_length=50
)
student_last_name = models.CharField(
'Student Last Name',
max_length=50
)
student_date_of_birth = models.DateField(
'Student Date Of Birth'
)
def __str__(self):
return f'Student: {self.student_first_name} {self.student_last_name}'
So here we have a DateField
for student_date-of_birth. This DateField is used to store dates in a database.
We can add DateInput
widget in Django forms in 3 ways.
Method1.
# forms.py
class StudentProfileForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['student_date_of_birth'].widget = forms.widgets.DateInput(
attrs={
'type': 'date', 'placeholder': 'yyyy-mm-dd (DOB)',
'class': 'form-control'
}
)
class Meta:
model = StudentProfile
fields = '__all__'
Inside the __init__
method, the super()
method is called to initialize the parent ModelForm
class. Then, the student_date_of_birth
field of the form is accessed and its widget is set to a DateInput
widget. The attrs
attribute of the widget is set to a dictionary containing the type
, placeholder
, and class
attributes of the widget.
Method2.
# forms.py
class StudentProfileForm(forms.ModelForm):
class Meta:
model = StudentProfile
fields = '__all__'
widgets = {
'student_date_of_birth': forms.DateInput(
attrs={'type': 'date', 'placeholder': 'yyyy-mm-dd (DOB)', 'class': 'form-control'}
)
}
The widgets
attribute inside the Meta
class is used to specify the widgets that should be used for the form fields. In this case, we are specifying that the student_date_of_birth
field should use the DateInput
widget, and we are setting the type
attribute of the widget to date,
placeholder to yyyy-mm-dd (DOB) and class
to form-control. This will render a date input field in the form when it is rendered in the template.
Method3. (not recommended)
Note: This method is not recommended. The StudentProfileForm
class defines student_date_of_birth
fields that are duplicates of the student_date_of_birth
field that already exists in the StudentProfile model. This is unnecessary and can lead to confusion and errors.
# forms.py
class StudentProfileForm(forms.ModelForm):
student_date_of_birth = forms.DateField(widget=forms.widgets.DateInput(
attrs={'type': 'date', 'placeholder': 'yyyy-mm-dd (DOB)', 'class': 'form-control'})
)
class Meta:
model = StudentProfile
fields = '__all__'
This is the template that I am using to display our StudentProfileForm
. I am using bootstrap5.
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Create Your Profile</title>
</head>
<body>
<h1>Create Your Profile</h1>
<div class="container">
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>
</html>
Conclusion.
We demonstrated three different approaches to add a date input widget to your Django forms in this blog post. We demonstrated how to use the Django-provided DateInput widget step-by-step and how to modify it to suit your project's requirements. You may enhance your forms' usability and aesthetics and give website users a better user experience by utilizing a date input widget. Take a look at the difference it can make for your project by giving it a try!
That's it. If you find it useful then show some love and support by clapping or by buying me coffee. And don't forget to share it with your friends. In case of any problem, you can comment here or you can also directly approach me through my LinkedIn.
Related Articles.
Mastering form validation in Django: A complete guide
How to add class and other attributes to django form fields
I would greatly appreciate it if you subscribe to my YouTube channel, Let's Code More