Opened 8 years ago

Closed 8 years ago

Last modified 5 years ago

#8156 closed (fixed)

UnicodeEncodeError on repr of UploadedFile with unicode name

Reported by: Karen Tracey Owned by: marco
Component: File uploads/storage Version: master
Severity: Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:

Description

If I create an UploadedFile with a unicode name that contains non-ASCII chars, I get a UnicodeEncodeError attempting to display its representation in a Python shell:

>>> from django.core.files.uploadedfile import UploadedFile
>>> uf = UploadedFile(name=u'¿Cómo',content_type='text')
>>> uf
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xbf' in position 15: ordinal not in range(128)
>>> uf.__repr__()
u'<UploadedFile: \xbfC\xf3mo (text)>'
 

The implementation of __repr__ here is:

    def __repr__(self):
        return "<%s: %s (%s)>" % (self.__class__.__name__, self.name, self.content_type)

I think __repr__ for UploadedFile needs to take into account the fact that the file name may be Unicode with non-ASCII chars and convert it into an ASCII-only representation before including it in the return value. As it is this implementation returns unicode, where I thought __repr__ was supposed to return only a string (per http://docs.python.org/ref/customization.html "The return value must be a string object.")?

Attachments (2)

uploadfile_repr.diff (645 bytes) - added by marco 8 years ago.
uploadedfile.diff (560 bytes) - added by Julian Bez 8 years ago.
encode to ascii

Download all attachments as: .zip

Change History (8)

comment:1 Changed 8 years ago by Jacob

Component: Core frameworkFile uploads/storage
Needs documentation: unset
Needs tests: unset
Patch needs improvement: unset
Triage Stage: UnreviewedAccepted

comment:2 Changed 8 years ago by marco

Owner: changed from nobody to marco
Status: newassigned

comment:3 Changed 8 years ago by marco

hi, this is my first patch :)

this patch checks if the name is unicode, and if it is, uses its repr instead.

Changed 8 years ago by marco

Attachment: uploadfile_repr.diff added

comment:4 Changed 8 years ago by marco

Has patch: set

Changed 8 years ago by Julian Bez

Attachment: uploadedfile.diff added

encode to ascii

comment:5 Changed 8 years ago by Jacob

Resolution: fixed
Status: assignedclosed

(In [8636]) FIxed #8156: UploadedFile.__repr__ now returns a string, a good __repr__ should.

comment:6 Changed 5 years ago by Jacob

milestone: 1.0

Milestone 1.0 deleted

Note: See TracTickets for help on using tickets.
Back to Top