Opened 15 years ago

Closed 15 years ago

#11819 closed (invalid)

Should __unicode__ be used when returning purely numerical values?

Reported by: sampablokuper Owned by: nobody
Component: Documentation Version: 1.1
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

http://docs.djangoproject.com/en/dev/intro/tutorial01/#playing-with-the-api says, "It's important to add __unicode__() methods to your models, not only for your own sanity when dealing with the interactive prompt, but also because objects' representations are used throughout Django's automatically-generated admin."

However, if I have a class like the following:

class C19Year(models.Model):
    value = IntegerRangeField(min_value=1800, max_value=1899)
    def __unicode__(self):
            return self.value

(where IntegerRangeField is as given here), I receive the following TemplateSyntaxError in the admin:

Caught an exception while rendering: coercing to Unicode: need string or buffer, int found

So, evidently the manual ought to explain that __unicode__ shouldn't be used when returning purely numerical values, or that such values ought to be converted to strings. (Of these two solutions, I'm not sure which is best.)

Change History (2)

comment:1 by sampablokuper, 15 years ago

For example,

class C19Year(models.Model):
    value = IntegerRangeField(min_value=1800, max_value=1899)
    def __unicode__(self):
            return str(self.value)

works, but is this the best solution? Whatever the best solution is, should go into the docs as recommended practice.

comment:2 by mrts, 15 years ago

Resolution: invalid
Status: newclosed

There's nothing Django-specific in __unicode__ and it's sufficiently documented (answering your question among other things) in general
Python docs:

Called to implement unicode() builtin; should return a Unicode object. When this method is not defined, string conversion is attempted, and the result of string conversion is converted to Unicode using the system default encoding.

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