1

django の認証モデルを拡張し、OneToOneField を介していくつかの特別なフィールドをユーザーに追加しようとしています。

from django.db import models
from django.contrib.auth.models import User


class GastroCustomer(models.Model):
    user = models.OneToOneField(User)
    barcode = models.IntegerField()
    balance = models.IntegerField()

    def __unicode__(self):
        return self.user

これは、管理モジュールの外部で正常に機能しています。しかし、管理インターフェイスを介して新しいものを追加し始めると、次のように表示されGastroCustomerます。 'User' object has no attribute '__getitem__'

__unicode__(self)たとえば、単純なものに変更した場合

def __unicode__(self):
    return "foo"

このエラーは発生しません。このユーザーフィールドが何らかの無効な状態にあるときを把握し、この場合の文字列表現を変更する方法はありますか? __unicode__(self)レコードが「正しい」前に呼び出される理由を誰か想像できますか?

4

1 に答える 1

2

Your model is actually returning a model object in __unicode__ method instead it should return unicode string, you can do this:

def __unicode__(self):
    return unicode(self.user)

This will call User.__unicode__ which will return user.username. Thanks to Nathan Villaescusa on his answer.

Alternatively you can directly return the username of user in __unicode__ method:

def __unicode__(self):
    return self.user.username
于 2013-04-19T19:03:09.570 に答える