Creating a Django Date Picker Widget Tutorial

Creating a Django Date Picker Widget Tutorial

Django Date Picker

Django Date Picker Widget Tutorial

In this Django Date Picker tutorial, we’ll cover how to use a widget to make your django date field form fields more cosmetically pleasing. We’ll also cover how to only allow certain date values to be accepted by your form.

The default django date field form:
Django Date Picker Default Date Field

Using the blank ModelForm date field is fine for beginners, but it doesn’t add much to the site. Since you’re on this page, I’m assuming you’re wanting to brighten up your webpage with some widgets.

Brief reminder of getting the base date field:

Models.py

In your models.py file, create a model with a field type DateField – Remember to import models to use DateField from django.db

I’ll provide my code below to make it easier to alter to your own purposes.

Django Date picker widget - Default

event_date = models.DateField(blank=False,)

I call mine event_date in this example. I also set blank=False to ensure I get a value whenever a user submits the form. 

Forms.py

2. Render your model as a form in your forms.py file. My model is ‘startcampaign’ and I’m using it as a form using Django’s ModelForm. 

Django Date Picker ModelForm

class StartCampaignsForm(forms.ModelForm):
class Meta:
model = startcampaign
exclude =[‘owner’,’active’]

Views.py

3. Next, you will need to create a view which will pass your form to your specific html file that you’re using. I have a lot of extra stuff in this screen shot, but the important part is to pass your form whenever the page is requested. 

Django Date Picker - views.py

def register(request):
   if request.method == ‘POST’:
      form = StartCampaignsForm(request.POST)
      if form.is_valid():
      redirect(‘home’)
   else:
      form = StartCampaignsForm()
      return render(request, ‘Campaigns/register.html’, {‘form’: form})

As a little side note here, I use a decorator ( @login_required) that means the user must be logged in to submit this form. You do not want to use this if you’re creating a register user form. This form is a form that I’m using only for logged in users to create content on my site. 

Additionally, I wanted to set an ‘owner’ field on my form to automatically be assigned to the user submitting the form. I did this through not commiting the form at first, assigning the variable owner to the requester.user, and then manually saving the form. 

Like I said though, the import part of the view for this example is naming the form as your form name, and then rendering it to your html. 

template.html

4. Since we rendered the form as ‘form’ we just call it using {{form.field_name}} – My field name is ‘event_date’ in our templates/html file.

Django Date Picker - rendering Fields

{% csrf_token %}

{{form.event_date}}

There we go, we’re caught up to speed if you weren’t there. Now the good stuff.

Instead of trying to make something like this ourselves, let’s use one that already has the functionality that we want. Jquery has one that will do exactly what I want it to do. Follow this link for the Source Code.

There are plenty of other cool little bits of code on this site as well if you want to find extra functionalities for your website. We’ll focus on the date picker for now. 

Django Date Picker Source Code

<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css”>
<link rel=”stylesheet” href=”/resources/demos/style.css”>
<script src=”https://code.jquery.com/jquery-1.12.4.js”></script>
<script src=”https://code.jquery.com/ui/1.12.1/jquery-ui.js”></script>
<script>
$( function() {
$( “#datepicker” ).datepicker();
} );
</script>

Adding source code to your Django project

Firstly, copy the source code from the link provided above. I’m extending from a base.html file on the template that I’m putting my form on. So I put the Jquery source code on that page. If you’re not extending, feel free to input the code on whatever html file you’re putting your form on.

Django Date Picker - Source Code in base.html

<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css”>
<link rel=”stylesheet” href=”/resources/demos/style.css”>
<script src=”https://code.jquery.com/jquery-1.12.4.js”></script>
<script src=”https://code.jquery.com/ui/1.12.1/jquery-ui.js”></script>
<script>
$( function() {
$( “#id_event_date” ).datepicker();
} );
</script>

Now, notice the green text below the ‘function()’ is edited to the field name of what I’m applying the datepicker to, along with ‘id_’ before. Django does this implicitly, so to match the variable we have to do the same. 

If you were to run this, you would see that it is still not applying the widget we want to the date field. This is because we have to make a change to our ModelForm field. The datepicker widget will look for a class called datepicker to apply the widget to. Let’s go back and fix that in our forms.py file:

Assigning Field to Widget
Django Date Picker modelform Edit

class StartCampaignsForm(forms.ModelForm):
class Meta:
model = startcampaign
widgets = {‘event_date’: forms.DateInput(attrs={‘class’: ‘datepicker’})}
exclude =[‘owner’,’active’]

Now, when we render the page of the form, we’ll get a little widget upon clicking into the date field form input area. Solid, that’s what we wanted. But now we have a different issue. The application that I’m using this field for needs to only allow future dates. Currently, even if you put a past date into the field it is accepted. Let’s fix that as well.

There’s two ways to do this, one is we can use the built in functionality of Jquery’s datepicker widget and apply a minimum and maximum date value. 

Specify Range of Datepicker
Django Date Picker - Min and Max Date Value

<script>
$( function() {
$( “#id_event_date” ).datepicker({ minDate: 0, maxDate: “+24M” });
} );
</script>

Here, we’re saying that the minDate is today, and that the max date is 24 months from today. 

The only thing with this application, is that the field is still editable within the blank without the date picker application.  There’s nothing here that says the form is invalid if a user goes back and manually edits the value either. We’ll use two separate means to make sure it works well. This takes care of the user interface side, let’s take care of it on the server side too. We’ll cover that in the next tutorial. But for now you’ve successfully implemented a widget into your Django Form field! Congrats!

Enjoy the Content? Sign up for the Newsletter!

Other jQuery Django Widget Tutorials:

4 thoughts on “Creating a Django Date Picker Widget Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *