tags:

views:

196

answers:

2

Why is a unicode function is required in models.py?

i.e,

def __unicode__(self)
    return sumid;
+2  A: 

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.

Dominic Rodger
Yeah thanks,,,i am familiar about python and syntax but i am definitely new to django.. Are there any other useful links than the usual django tutorial..Is so please guide me to it........I got an idea of wht it is...Thanks for all the replies........
Hulk
+1: Quote the documentation
S.Lott
@Hulk: What's wrong with the Django documentation? It's excellent. Some of the best there is. What's the problem?
S.Lott
Its a great documentation but the only thing is that beginner does not get much from it......Lets say for example (pk=1) what shd any one understand from this....
Hulk
+2  A: 

Hi, 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 :-)

SapphireSun
Yeah thanks,,,i am familiar about python and syntax but i am definitely new to django.. Are there any other useful links than the usual django tutorial..Is so please guide me to it........ I got an idea of wht it is... Thanks for all the replies........
Hulk
I wish I could point you to some other sources, but so far all I get is random blogs when I google error messages and such. I find the documentation is usually pretty good, you just have to run into a problem framed in the right way to get at why they did certain things.
SapphireSun
`sumid` seems to be undefined. Maybe you want to change it to `self.sumid`?
nosklo
Ah, good point, I'll make the change.
SapphireSun