Django

Code

Changeset 7323

Show
Ignore:
Timestamp:
03/19/08 17:29:11 (1 year ago)
Author:
jacob
Message:

Fixed #5894: added FilePathField? to newforms. Thanks, Alex Gaynor.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/AUTHORS

    r7316 r7323  
    147147    gandalf@owca.info 
    148148    Marc Garcia <marc.garcia@accopensys.com> 
     149    Alex Gaynor <alex.gaynor@gmail.com> 
    149150    Andy Gayton <andy-django@thecablelounge.com> 
    150151    Baishampayan Ghose 
  • django/trunk/django/db/models/fields/__init__.py

    r7274 r7323  
    843843        kwargs['max_length'] = kwargs.get('max_length', 100) 
    844844        Field.__init__(self, verbose_name, name, **kwargs) 
     845     
     846    def formfield(self, **kwargs): 
     847        defaults = { 
     848            'path': self.path, 
     849            'match': self.match, 
     850            'recursive': self.recursive, 
     851            'form_class': forms.FilePathField, 
     852        } 
     853        defaults.update(kwargs) 
     854        return super(FilePathField, self).formfield(**defaults) 
    845855 
    846856    def get_manipulator_field_objs(self): 
  • django/trunk/django/newforms/fields.py

    r7025 r7323  
    55import copy 
    66import datetime 
     7import os 
    78import re 
    89import time 
     
    3233    'BooleanField', 'NullBooleanField', 'ChoiceField', 'MultipleChoiceField', 
    3334    'ComboField', 'MultiValueField', 'FloatField', 'DecimalField', 
    34     'SplitDateTimeField', 'IPAddressField', 
     35    'SplitDateTimeField', 'IPAddressField', 'FilePathField', 
    3536) 
    3637 
     
    719720        raise NotImplementedError('Subclasses must implement this method.') 
    720721 
     722class FilePathField(ChoiceField): 
     723    def __init__(self, path, match=None, recursive=False, required=True, 
     724                 widget=Select, label=None, initial=None, help_text=None, 
     725                 *args, **kwargs): 
     726        self.path, self.match, self.recursive = path, match, recursive 
     727        super(FilePathField, self).__init__(choices=(), required=required, 
     728            widget=widget, label=label, initial=initial, help_text=help_text, 
     729            *args, **kwargs) 
     730        self.choices = [] 
     731        if self.match is not None: 
     732            self.match_re = re.compile(self.match) 
     733        if recursive: 
     734            for root, dirs, files in os.walk(self.path): 
     735                for f in files: 
     736                    if self.match is None or self.match_re.search(f): 
     737                        f = os.path.join(root, f) 
     738                        self.choices.append((f, f.replace(path, "", 1))) 
     739        else: 
     740            try: 
     741                for f in os.listdir(self.path): 
     742                    full_file = os.path.join(self.path, f) 
     743                    if os.path.isfile(full_file) and (self.match is None or self.match_re.search(f)): 
     744                        self.choices.append((full_file, f)) 
     745            except OSError: 
     746                pass 
     747        self.widget.choices = self.choices 
     748 
    721749class SplitDateTimeField(MultiValueField): 
    722750    default_error_messages = { 
  • django/trunk/docs/newforms.txt

    r7300 r7323  
    13341334An ``UploadedFile`` object has two attributes: 
    13351335 
    1336     ======================  ===================================================== 
    1337     Argument                Description 
    1338     ======================  ===================================================== 
     1336    ======================  ==================================================== 
     1337    Attribute               Description 
     1338    ======================  ==================================================== 
    13391339    ``filename``            The name of the file, provided by the uploading 
    13401340                            client. 
     1341                             
    13411342    ``content``             The array of bytes comprising the file content. 
    1342     ======================  ===================================================== 
     1343    ======================  ==================================================== 
    13431344 
    13441345The string representation of an ``UploadedFile`` is the same as the filename 
     
    13491350 
    13501351.. _`bind the file data to the form`: `Binding uploaded files to a form`_ 
     1352 
     1353``FilePathField`` 
     1354~~~~~~~~~~~~~~~~~ 
     1355 
     1356**New in Django development version** 
     1357 
     1358    * Default widget: ``Select`` 
     1359    * Empty value: ``None`` 
     1360    * Normalizes to: A unicode object 
     1361    * Validates that the selected choice exists in the list of choices. 
     1362    * Error message keys: ``required``, ``invalid_choice`` 
     1363 
     1364The field allows choosing from files inside a certain directory. It takes three 
     1365extra arguments: 
     1366 
     1367    ==============  ==========  =============================================== 
     1368    Argument        Required?   Description 
     1369    ==============  ==========  =============================================== 
     1370    ``path``        Yes         The absolute path to the directory whose  
     1371                                contents you want listed. This directory must  
     1372                                exist. 
     1373                             
     1374    ``recursive``   No          If ``False`` (the default) only the direct 
     1375                                contents of ``path`` will be offered as choices. 
     1376                                If ``True``, the directory will be descended 
     1377                                into recursively and all descendants will be 
     1378                                listed as choices. 
     1379                                 
     1380    ``match``       No          A regular expression pattern; only files with 
     1381                                names matching this expression will be allowed 
     1382                                as choices. 
     1383    ==============  ==========  =============================================== 
    13511384 
    13521385``ImageField`` 
  • django/trunk/tests/regressiontests/forms/fields.py

    r7294 r7323  
    11341134u'' 
    11351135 
     1136# FilePathField ############################################################### 
     1137 
     1138>>> import os 
     1139>>> from django import newforms as forms 
     1140>>> path = forms.__file__ 
     1141>>> path = os.path.dirname(path) + '/' 
     1142>>> path 
     1143'.../django/newforms/' 
     1144>>> f = forms.FilePathField(path=path) 
     1145>>> f.choices.sort() 
     1146>>> f.choices 
     1147[('.../django/newforms/__init__.py', '__init__.py'), ('.../django/newforms/__init__.pyc', '__init__.pyc'), ('.../django/newforms/fields.py', 'fields.py'), ('.../django/newforms/fields.pyc', 'fields.pyc'), ('.../django/newforms/forms.py', 'forms.py'), ('.../django/newforms/forms.pyc', 'forms.pyc'), ('.../django/newforms/models.py', 'models.py'), ('.../django/newforms/models.pyc', 'models.pyc'), ('.../django/newforms/util.py', 'util.py'), ('.../django/newforms/util.pyc', 'util.pyc'), ('.../django/newforms/widgets.py', 'widgets.py'), ('.../django/newforms/widgets.pyc', 'widgets.pyc')] 
     1148>>> f.clean('fields.py') 
     1149Traceback (most recent call last): 
     1150... 
     1151ValidationError: [u'Select a valid choice. That choice is not one of the available choices.'] 
     1152>>> f.clean(path + 'fields.py') 
     1153u'.../django/newforms/fields.py' 
     1154>>> f = forms.FilePathField(path=path, match='^.*?\.py$') 
     1155>>> f.choices.sort() 
     1156>>> f.choices 
     1157[('.../django/newforms/__init__.py', '__init__.py'), ('.../django/newforms/fields.py', 'fields.py'), ('.../django/newforms/forms.py', 'forms.py'), ('.../django/newforms/models.py', 'models.py'), ('.../django/newforms/util.py', 'util.py'), ('.../django/newforms/widgets.py', 'widgets.py')] 
     1158>>> f = forms.FilePathField(path=path, recursive=True, match='^.*?\.py$') 
     1159>>> f.choices.sort() 
     1160>>> f.choices 
     1161[('.../django/newforms/__init__.py', '__init__.py'), ('.../django/newforms/extras/__init__.py', 'extras/__init__.py'), ('.../django/newforms/extras/widgets.py', 'extras/widgets.py'), ('.../django/newforms/fields.py', 'fields.py'), ('.../django/newforms/forms.py', 'forms.py'), ('.../django/newforms/models.py', 'models.py'), ('.../django/newforms/util.py', 'util.py'), ('.../django/newforms/widgets.py', 'widgets.py')] 
     1162 
    11361163# SplitDateTimeField ########################################################## 
    11371164