1
0
mirror of https://github.com/django/django.git synced 2025-10-24 22:26:08 +00:00

newforms: Added Field.widget_attrs() hook, which lets a Field designate HTML attributes to use in its widget. Implemented CharField.widget_attrs(), which sets the HTML maxlength attribute for <input type='text'> and <input type='password'>. Thanks for the idea, Gary Doades

git-svn-id: http://code.djangoproject.com/svn/django/trunk@4187 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Adrian Holovaty
2006-12-08 18:54:53 +00:00
parent 4e72dc86ff
commit f10a910577
2 changed files with 59 additions and 14 deletions

View File

@@ -4,7 +4,7 @@ Field classes
from django.utils.translation import gettext
from util import ValidationError, smart_unicode
from widgets import TextInput, CheckboxInput, Select, SelectMultiple
from widgets import TextInput, PasswordInput, CheckboxInput, Select, SelectMultiple
import datetime
import re
import time
@@ -37,6 +37,12 @@ class Field(object):
widget = widget or self.widget
if isinstance(widget, type):
widget = widget()
# Hook into self.widget_attrs() for any Field-specific HTML attributes.
extra_attrs = self.widget_attrs(widget)
if extra_attrs:
widget.attrs.update(extra_attrs)
self.widget = widget
# Increase the creation counter, and save our local copy.
@@ -54,10 +60,18 @@ class Field(object):
raise ValidationError(gettext(u'This field is required.'))
return value
def widget_attrs(self, widget):
"""
Given a Widget instance (*not* a Widget class), returns a dictionary of
any HTML attributes that should be added to the Widget, based on this
Field.
"""
return {}
class CharField(Field):
def __init__(self, max_length=None, min_length=None, required=True, widget=None):
Field.__init__(self, required, widget)
self.max_length, self.min_length = max_length, min_length
Field.__init__(self, required, widget)
def clean(self, value):
"Validates max_length and min_length. Returns a Unicode object."
@@ -70,6 +84,10 @@ class CharField(Field):
raise ValidationError(gettext(u'Ensure this value has at least %d characters.') % self.min_length)
return value
def widget_attrs(self, widget):
if self.max_length is not None and isinstance(widget, (TextInput, PasswordInput)):
return {'maxlength': str(self.max_length)}
class IntegerField(Field):
def clean(self, value):
"""