Opened 5 years ago

Closed 5 years ago

#30811 closed Bug (invalid)

Django throws 'UnicodeEncodeError' when using Cyrillic symbols to override field upload_to.

Reported by: Kirill Owned by: Kirill
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords: UnicodeEncodeError, Cyrillic, upload_to, File, FileField
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Kirill)

So, I have a Book model, that contains some fields. But most important are:
'title' as 'CharField'
'pdf', 'epub', 'fb2' as 'FileField'
'image' as 'ImageField'
we will return to they in just a second...
My Book model also has overrided clean method. In that method I assign my title field value as upload_to value.

uploading_files = [
    self.image,
    self.pdf,
    self.fb2,
    self.epub
]
for file_ in uploading_files:
    file_.field.upload_to = self.title

Here is where bug hided. If I set title value to "Колобок", for example, it throws me an UnicodeEncodeError. This thing happends only when i first create model.
If I firstly will set title value as "Kolobok", and later rename it to "Колобок", I have no error.


I already some kind of "fixed" this.
Endpoint of thrown exception was ...\django\db\models\fields\files.py. After fork from your Github, I followed this path, and find function that throws that error, that function was generate_filename in FileField class, line 305. After I added small correct...

try:
    dirname = datetime.datetime.now().strftime(self.upload_to)
except UnicodeEncodeError:
    dirname = self.upload_to

... all works fine now, and I can use Cyrillic symbols as my title and folder name in upload_to attribute.


For comfort, here is my Github with all my Django code in it.

Change History (3)

comment:1 by Kirill, 5 years ago

Type: UncategorizedBug

comment:2 by Kirill, 5 years ago

Description: modified (diff)

comment:3 by Mariusz Felisiak, 5 years ago

Resolution: invalid
Status: assignedclosed
Version: 2.2master

Thanks for this report, however I don't think that it is an issue in Django, but rather in your implementation if you want to set upload_to dynamically you should set it to a callable, e.g.

def callable_upload_to(instance, filename):
    return posixpath.join(instance.title, filename)

class Book(models.Model):
    pdf = FileField(..., upload_to=callable_upload_to)
    ...
Note: See TracTickets for help on using tickets.
Back to Top