Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why __unicode__ doesn't work but __str__ does?

I'm trying to break some rock by developing a website on my own, and I'm starting by creating some registry pages and listing database records.

I'm getting bugged with the fact that __unicode__ method doesn't print the username of my records and __str__ does!

I know that using __unicode__ is the best practice to have, but I can only print my object username with __str__.

Can anybody explain why this happens?

My Model:

from django.db import models

class User(models.Model):
    username = models.CharField(max_length=200)
    reg_date = models.DateTimeField('registry date')

    def __unicode__(self):
        return self.username

My admin.py:

from django.contrib import admin
from registo.models import User

admin.site.register(User)

My __unicode__(self) output:

User
    User object

My __str__(self) output:

User
    Teste

Thanks for your cooperation in advance!

like image 463
Sammy Avatar asked Aug 12 '13 14:08

Sammy


2 Answers

it looks like you are using Python3.x and here is the relevant documentation on Str and Unicode methods

In Python 2, the object model specifies __str__() and __unicode__() methods. If these methods exist, they must return str (bytes) and unicode (text) respectively.

The print statement and the str() built-in call __str__() to determine the human-readable representation of an object. The unicode() built-in calls __unicode__() if it exists, and otherwise falls back to __str__() and decodes the result with the system encoding. Conversely, the Model base class automatically derives __str__() from __unicode__() by encoding to UTF-8.

In Python 3, there’s simply __str__(), which must return str (text).

So

On Python 3, the decorator is a no-op. On Python 2, it defines appropriate __unicode__() and __str__() methods (replacing the original __str__() method in the process).

like image 88
karthikr Avatar answered Nov 07 '22 10:11

karthikr


If it's not the python 3 thing, your code as posted has incorrect indentation - not sure if copy/pasting bug or if that's how it is in the code. But your User model's methods need to be indented, like so:

from django.db import models

class User(models.Model):
    username = models.CharField(max_length=200)
    reg_date = models.DateTimeField('registry date')

    def __unicode__(self):
        return self.username
like image 2
AdamKG Avatar answered Nov 07 '22 12:11

AdamKG