Skip to content

Commit

Permalink
Fixed #29529 -- FilePathField path parameter now accepts a callable.
Browse files Browse the repository at this point in the history
  • Loading branch information
jajce committed Feb 3, 2019
1 parent 3634560 commit 7e4677d
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
2 changes: 1 addition & 1 deletion django/db/models/fields/__init__.py
Expand Up @@ -1712,7 +1712,7 @@ def get_prep_value(self, value):

def formfield(self, **kwargs):
return super().formfield(**{
'path': self.path,
'path': self.path() if callable(self.path) else self.path,
'match': self.match,
'recursive': self.recursive,
'form_class': forms.FilePathField,
Expand Down
13 changes: 13 additions & 0 deletions docs/ref/models/fields.txt
Expand Up @@ -868,6 +868,19 @@ directory on the filesystem. Has three special arguments, of which the first is
Required. The absolute filesystem path to a directory from which this
:class:`FilePathField` should get its choices. Example: ``"/home/images"``.

A callable (such as a function) can also be passed to dynamically set the
path at runtime::

def generate_path():
return os.path.join(settings.LOCAL_FILE_DIR, '/images')

file = models.FilePathField(path=generate_path)

.. versionchanged:: 3.0

Older versions don't allow passing a callable.


.. attribute:: FilePathField.match

Optional. A regular expression, as a string, that :class:`FilePathField`
Expand Down
26 changes: 26 additions & 0 deletions tests/model_fields/test_filepathfield.py
@@ -0,0 +1,26 @@
import os.path

from django.db.models import FilePathField
from django.test import TestCase

PATH = os.path.dirname(os.path.abspath(__file__))


def generate_path():
return PATH


class FilePathFieldTests(TestCase):

def test_string(self):
fp = FilePathField(path=PATH)
self.assertEqual(PATH, fp.path)

def test_callable(self):
fp = FilePathField(path=generate_path)
self.assertEqual(PATH, fp.path())

def test_formfield(self):
fp = FilePathField(path=generate_path)
formfield = fp.formfield()
self.assertEqual(formfield.path, PATH)

0 comments on commit 7e4677d

Please sign in to comment.