[Fixed]-Use of unicode in Django


It’s not. If you define a __unicode__() method, Django will call it when it needs to render an object in a context where a string representation is needed (e.g. in the model’s admin pages).

The documentation says:

The __unicode__() method is called
whenever you call unicode() on an
object. Since Django’s database
backends will return Unicode strings
in your model’s attributes, you would
normally want to write a __unicode__()
method for your model.


I’m a bit new to Django, but I think I can help you.

First, it isn’t exactly required, but it’s a really good idea. The field is used to create representations of your objects in the Django admin (otherwise they all have the same name :-P) and when you print out an object to your terminal window to see what’s going on (otherwise you get a generic mostly useless message).

Second, from what you wrote, it looks like you’re new to Python. I recommend reading some Python tutorials on class syntax. Also, semicolons aren’t necessary in this language. The correct syntax for creating the unicode method is:

class Foo(models.Model):
    # Model fields go here

    def __unicode__(self):
        return u"%i" % self.sumid

The __unicode__ method has double underscores because it is a special function, namely when the builtin function unicode( obj ) is called on it, it returns a unicode string representation of that object (sort of like java’s ToString).

I hope this helps 🙂


I think the others have given some detailed explanations that should be more than enough for you. But here’s a straightforward answer: __unicode__() is equivalent to toString() in Java (and many other languages)

Leave a comment