2

Django Widgets set HTML5 maxlength attribute, based on the Model max_length.

class Publication(models.Model):
    name = models.CharField(max_length=255)

<input maxlength="255" required="" id="id_name" type="text">

I want to remove this attribute, because is interfering with my own validation, which is more complex.

I know that required attribute can be set to false, but I don't know for other html5 attributes.

I want to apply them in multiple forms to different fields.

Modifying the form init is ok, but not very scalable.

A base class and inheritance is an option, but I don't want to applied to all fields.

I'm looking for something like required=false, to apply to multiple fields.

user3541631
  • 3,686
  • 8
  • 48
  • 115

2 Answers2

4

Here is a Form example from a Book model. I bring in one field called title. In the init method I pop the maxlength attribute for that field. When you go into the HTML there is no maxlength attribute.

from django import forms
from .models import Book

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ('title',)

    def __init__(self, *args, **kwargs):
        super(BookForm, self).__init__(*args, **kwargs)
        self.fields['title'].widget.attrs.pop('maxlength', None)
yoyoyoyo123
  • 2,362
  • 2
  • 22
  • 36
  • so there is no simple method, I want to apply to specific fields in multiple forms – user3541631 Mar 01 '18 at 14:20
  • not that I know of. You could just create a simple function that takes the dictionary and pops maxlength but you still need __init__...If i understand what you are saying – yoyoyoyo123 Mar 01 '18 at 14:22
  • ok thanks, I was searching for something like, required=false(exist in Django), and have on the field maxlength=false. – user3541631 Mar 01 '18 at 14:24
3

I was solving this recently. I did this in my forms.py:

from django import forms


class ContactForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=50, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter Name'}))
    your_surname = forms.CharField(required=False,label='Your surname', max_length=50, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter Surname'}))


    # Remove html5 attr from input field
    your_name.widget.attrs.pop('maxlength', None)

Only for info, this is valid for Forms not ModelForms.

TomRavn
  • 1,134
  • 14
  • 30