views:

749

answers:

1

I'm working on a Django app for hosting media (specifically audio and images). I have image galleries and photos separate in my model, and have them linked with a ForeignKey (not sure if that's correct, but still learning). What I need is for the Album class's __unicode__ to return the album owner's username.

class Album(models.Model):
    artist = models.ForeignKey(User, unique=True, related_name='artpunk')

    def __unicode__(self):
        return self.artist.username

I know the username property exists, and confirmed it by inserting a dir() and checking the console output. The problem is when I enter the image section of the admin panel, it simply states "Unrecognised command." Can User properties not be accessed by models? Or am I doing something else wrong?

EDIT: Forgot to mention, using Python 2.6 with Django 1.0.2. The exact text of the error is, as above, simply "Unrecognised command" in bold, and I've already run syncdb without issue. However, I reran syncdb (gave no output) this morning just to try again and now it seems to be working fine.

It's reproducible by changing the following:

    def __unicode__(self):
        return self.artist.username

To something like this:

    def __unicode__(self):
        return self.artist.username+'\'s Gallery'
+1  A: 

There should be no problem accessing the user (even as a foreign key) from a model. I just finished testing it out myself, and there doesn't appear to be any significant difference.

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

On a side note, you should also just be able to return self.artist, since I believe that User.__unicode__() returns the username anyway.

What are the exact details of the error? What version of Django/Python are you using? Did you make a change to your model that's not yet reflected in the database? Sometimes I've noticed you just need to restart the test server for things to work well. Particularly in the admin.

In response to your edit, try casting the username as a string:

str(self.user.username)
Alex Jillard
or even better use a unicode string so that the unicode method actually returns a unicodestring :-) return self.artist.username+u'\'s Gallery'
Mr Shark