Unable to save model with ImageField/FileField on Windows
|Reported by:||anonymous||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||master|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Given the model, on Windows:
class StaffMember(models.Model): name = models.CharField(max_length=100, unique=True) photo = models.ImageField(upload_to="img/staff/", blank=True) #...
A validation error is raised whenever attempting to save from within the Django Admin interface. I found ticket #2923 and the issue seemed similar so I ran some tests on the code in django/db/models/fields/init.py. In the function "isWithinMediaRoot" "field_data" has a forward slash appended to the start of the path. On Windows "os.path.join" only returns the path after that leading forward slash resulting in an incorrect absolute path and a ValidationError. If you strip out the leading forward slash the absolute path is correctly determined.
Example (Python 2.5):
>>> root = 'F:\\root\\' # slash orientation doesn't matter here as far as os.path.join is concerned. >>> path = '/path/to/file.txt' >>> os.path.join(root, path) '/path/to/file.txt' >>> path = 'path/to/file.txt' >>> os.path.join(root, path) 'F:\\root\\path/to/file.txt'