Skip to content

Commit

Permalink
Fixed #29529 -- Allowed models.fields.FilePathField to accept a calla…
Browse files Browse the repository at this point in the history
…ble path.
  • Loading branch information
jajce authored and felixxm committed May 2, 2019
1 parent 11971cd commit ef082eb
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 1 deletion.
2 changes: 1 addition & 1 deletion django/db/models/fields/__init__.py
Expand Up @@ -1709,7 +1709,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
17 changes: 17 additions & 0 deletions docs/ref/models/fields.txt
Expand Up @@ -868,6 +868,23 @@ 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"``.

``path`` may also be a callable, such as a function to dynamically set the
path at runtime. Example::

import os
from django.conf import settings
from django.db import models

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

class MyModel(models.Model):
file = models.FilePathField(path=images_path)

.. versionchanged:: 3.0

``path`` can now be a callable.

.. attribute:: FilePathField.match

Optional. A regular expression, as a string, that :class:`FilePathField`
Expand Down
2 changes: 2 additions & 0 deletions docs/releases/3.0.txt
Expand Up @@ -206,6 +206,8 @@ Models

* ``connection.queries`` now shows ``COPY … TO`` statements on PostgreSQL.

* :class:`~django.db.models.FilePathField` now accepts a callable ``path``.

Requests and Responses
~~~~~~~~~~~~~~~~~~~~~~

Expand Down
10 changes: 10 additions & 0 deletions tests/model_fields/test_filepathfield.py
Expand Up @@ -10,3 +10,13 @@ def test_path(self):
field = FilePathField(path=path)
self.assertEqual(field.path, path)
self.assertEqual(field.formfield().path, path)

def test_callable_path(self):
path = os.path.dirname(__file__)

def generate_path():
return path

field = FilePathField(path=generate_path)
self.assertEqual(field.path(), path)
self.assertEqual(field.formfield().path, path)

0 comments on commit ef082eb

Please sign in to comment.