Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create input mask for use in django forms

Tags:

jquery

django

Good evening. I'm needing to figure out how to apply input masks in django's forms to a project, however, none of the previous attempts as successful. On the last test: from input_mask.widgets import InputMask However, perhaps for inexperience on my part, when using it not achieved in the desired result. What will be the mistake? Or in another case how do I use other alternatives to deal with this problem? Thank you very much in advance.

like image 754
Luiz Júnior Avatar asked Oct 23 '25 16:10

Luiz Júnior


1 Answers

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.

like image 115
Josh Kot Sheiss Avatar answered Oct 26 '25 07:10

Josh Kot Sheiss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!