Skip to content

Commit b990574

Browse files
committed
model fields get_prep_value should accept string
One of the cases when the value is a string is migration generation with default value. Fix: #51
1 parent 62c01cb commit b990574

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

filebrowser/fields.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# coding: utf-8
22
import os
33

4+
from six import string_types
5+
46
from django import forms
57
try:
68
from django.urls import reverse
@@ -111,7 +113,7 @@ def from_db_value(self, value, expression, connection, context):
111113
return self.to_python(value)
112114

113115
def get_prep_value(self, value):
114-
if not value:
116+
if not value or isinstance(value, string_types):
115117
return value
116118
return value.path
117119

@@ -248,8 +250,8 @@ def to_python(self, value):
248250
return value
249251
return FileObject(value, site=self.site)
250252

251-
def get_db_prep_value(self, value, connection, prepared=False):
252-
if not value:
253+
def get_prep_value(self, value):
254+
if not value or isinstance(value, string_types):
253255
return value
254256
return value.path
255257

tests/test_fields.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# coding: utf-8
2+
3+
from tests import FilebrowserTestCase as TestCase
4+
5+
from six import string_types
6+
7+
from filebrowser.base import FileObject
8+
from filebrowser.fields import FileBrowseField
9+
10+
11+
class FileBrowseFieldTests(TestCase):
12+
path_to_file = "/path/to/file.jpg"
13+
14+
def test_to_python(self):
15+
field = FileBrowseField()
16+
17+
# should deal gracefully with any of the following arguments:
18+
# An instance of the correct type, a string, and None (if the field allows null=True)
19+
values = [FileObject(self.path_to_file), self.path_to_file]
20+
for v in values:
21+
actual = field.to_python(v)
22+
self.assertIsInstance(actual, FileObject)
23+
self.assertEqual(actual.path, self.path_to_file)
24+
self.assertEqual(field.to_python(None), None)
25+
26+
def test_get_prep_value(self):
27+
field = FileBrowseField()
28+
29+
# similar to to_python() should handle all 3 cases
30+
values = [FileObject(self.path_to_file), self.path_to_file]
31+
for v in values:
32+
actual = field.get_prep_value(v)
33+
self.assertIsInstance(actual, string_types)
34+
self.assertEqual(actual, self.path_to_file)
35+
self.assertEqual(field.to_python(None), None)

0 commit comments

Comments
 (0)