[Django]-Create input mask for use in django forms

7👍

Good news! This is actually pretty easy. In your template, make sure you include JQuery as follows:

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.10/jquery.mask.js"></script>

Then when creating a form field, simply pass the input mask into a field like so:

contact_number = forms.CharField(widget=forms.TextInput(attrs={'data-mask':"000-000-0000"}))

Or if you’re using a ModelForm, you can place it in the Meta like so:

class Meta:
    model = Booking
    fields = ('date', 'contact_number')

    widgets = {'contact_number': forms.TextInput(attrs={'data-mask':"000-000-0000"})}

Check out https://dobsondev.com/2017/04/14/using-jquery-mask-to-mask-form-input/ if you want to get more information on how to use the JQuery masks beyond the simple example given here.

Leave a comment