﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
22206	TextField doesn't set max_length attribute on its formfield, unlike CharField	Chris Wilson	Chris Wilson	"In django/db/models/fields/__init__.py, the CharField field type constructs its widgets with a max_length parameter, which ends up in the widget:

{{{
class CharField(Field): # django.db.forms.fields
    def formfield(self, **kwargs):
        # Passing max_length to forms.CharField means that the value's length
        # will be validated twice. This is considered acceptable since we want
        # the value in the form field (to pass into widget for example).
        defaults = {'max_length': self.max_length}
        defaults.update(kwargs)
        return super(CharField, self).formfield(**defaults)

class CharField(Field): # django.forms.fields
    def widget_attrs(self, widget):
        attrs = super(CharField, self).widget_attrs(widget)
        if self.max_length is not None and isinstance(widget, TextInput):
            # The HTML attribute is maxlength, not max_length.
            attrs.update({'maxlength': str(self.max_length)})
        return attrs
}}}

But nothing like this happens for the TextField database field, which creates a TextField form field, which uses a Textarea widget by default:

{{{
class TextField(Field):
    description = _(""Text"")

    def formfield(self, **kwargs):
        defaults = {'widget': forms.Textarea}
        defaults.update(kwargs)
        return super(TextField, self).formfield(**defaults)
}}}

I think that TextField doesn't override form_class, so it gets the default CharField from Field.formfield(), as CharField does, but with a custom widget. So all we'd need to do is set the attribute in the CharField db field:

{{{
    def formfield(self, **kwargs):
        # Passing max_length to forms.CharField means that the value's length
        # will be validated twice. This is considered acceptable since we want
        # the value in the form field (to pass into widget for example).
        defaults = {'max_length': self.max_length}
        defaults.update(kwargs)
        return super(TextField, self).formfield(**defaults)
}}}

and add the attribute to the widget in CharField:

{{{
    def widget_attrs(self, widget):
        attrs = super(CharField, self).widget_attrs(widget)
        if self.max_length is not None: # all types of widgets, not hard coded
            # The HTML attribute is maxlength, not max_length.
            attrs.update({'maxlength': str(self.max_length)})
        return attrs
}}}"	New feature	closed	Forms	dev	Normal	fixed			Accepted	1	0	0	0	0	0
