How to Create a Date Form Field in a Django Form 


               


How to Create a Date Form Field in a Django Form



Python


In this article, we show how to create a date form field in a Django form.

By a date form field, what is meant is a field in which a user can specify the full date, including day, month, and year.

How this field is rendered depends on the browser, but it will usually appear as a drop-down list for each the day, month, and year.

So how can we create this date form field in a Django form?

So, below we show the code how to create this date form field in Django.



So, we have a form named UserForm.

In this form, we create a field named birth_date. This form field is of type DateField. We add a label set to, "What is your birth date?"

We then set widget equal to, forms.SelectDateWidget

This makes the form field a Date Field with day, month, and year selection options.

This form will be rendered as the following below.

Date form field in a Django Form

However, if you look at this date form field, as is, you may notice a few problems with it.

One problem is it begins with the year 2017.

If you're reading this form, chances are you weren't born in the year 2017.

We need a way to specify the range of years that the date form field should cover.

So we have to add some code to the above code.


How to Specify the Range of Years in the Date Form Field

Let's say we want the years to range from 1940 to 2020, let's just say.

The code shown below does this.



So we created a variable named YEARS. This variable YEARS is a list.

In this line, we declare a variable named x and specified for it to be the range from 1940 to 2021.

Then inside of the widget=forms.SelectDateWidget(), we put years=YEARS.

This gives us the range 1940 to 2020.

This is shown in the output below.

Date form field with the year range specified in a Django Form




How to Specify an Initial Date

One last thing we could do is specify the initial date shown when the page is first loaded.

Even though you may have a range from 1940 to 2017, or whatever, the average user to your site may be a 20-something-year-old. Therefore, you may want to specify a date that's like in the 1980s or 1990s.

With Django, you can do this.

The code below specifies the initial date to be June 21, 1990.



When the page first loads, this is what will appear at the output, shown below.

Date form field with an initial date specified in a Django Form

So, this is a few of the things we can do to a date form field in a Django form.

We can create it, specify a range of years, specify an initial date, and so on.

We'll show in a later tutorial how to retrieve data from a date form field in a Django form.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...