summaryrefslogtreecommitdiff
path: root/django/newforms/fields.py
diff options
context:
space:
mode:
authorJacob Kaplan-Moss <jacob@jacobian.org>2008-03-19 22:29:11 +0000
committerJacob Kaplan-Moss <jacob@jacobian.org>2008-03-19 22:29:11 +0000
commit4457ba002d64d4a991b0561c5be69a8c61b2b828 (patch)
tree6251d21048f862d93fc9f011c40d3e63e87b46c5 /django/newforms/fields.py
parentbc1f67a6de45fe2ebfdf69ba449295066f365419 (diff)
Fixed #5894: added FilePathField to newforms. Thanks, Alex Gaynor.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7323 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'django/newforms/fields.py')
-rw-r--r--django/newforms/fields.py30
1 files changed, 29 insertions, 1 deletions
diff --git a/django/newforms/fields.py b/django/newforms/fields.py
index bc3e543037..08e8b842ec 100644
--- a/django/newforms/fields.py
+++ b/django/newforms/fields.py
@@ -4,6 +4,7 @@ Field classes.
import copy
import datetime
+import os
import re
import time
# Python 2.3 fallbacks
@@ -31,7 +32,7 @@ __all__ = (
'RegexField', 'EmailField', 'FileField', 'ImageField', 'URLField',
'BooleanField', 'NullBooleanField', 'ChoiceField', 'MultipleChoiceField',
'ComboField', 'MultiValueField', 'FloatField', 'DecimalField',
- 'SplitDateTimeField', 'IPAddressField',
+ 'SplitDateTimeField', 'IPAddressField', 'FilePathField',
)
# These values, if given to to_python(), will trigger the self.required check.
@@ -718,6 +719,33 @@ class MultiValueField(Field):
"""
raise NotImplementedError('Subclasses must implement this method.')
+class FilePathField(ChoiceField):
+ def __init__(self, path, match=None, recursive=False, required=True,
+ widget=Select, label=None, initial=None, help_text=None,
+ *args, **kwargs):
+ self.path, self.match, self.recursive = path, match, recursive
+ super(FilePathField, self).__init__(choices=(), required=required,
+ widget=widget, label=label, initial=initial, help_text=help_text,
+ *args, **kwargs)
+ self.choices = []
+ if self.match is not None:
+ self.match_re = re.compile(self.match)
+ if recursive:
+ for root, dirs, files in os.walk(self.path):
+ for f in files:
+ if self.match is None or self.match_re.search(f):
+ f = os.path.join(root, f)
+ self.choices.append((f, f.replace(path, "", 1)))
+ else:
+ try:
+ for f in os.listdir(self.path):
+ full_file = os.path.join(self.path, f)
+ if os.path.isfile(full_file) and (self.match is None or self.match_re.search(f)):
+ self.choices.append((full_file, f))
+ except OSError:
+ pass
+ self.widget.choices = self.choices
+
class SplitDateTimeField(MultiValueField):
default_error_messages = {
'invalid_date': _(u'Enter a valid date.'),