简体   繁体   English

Django模型:从当前登录的用户返回用户名

[英]Django Model: Returning username from currently logged in user

I'm working on a Django app for hosting media (specifically audio and images). 我正在开发用于托管媒体(特别是音频和图像)的Django应用。 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). 我的模型中有单独的图像画廊和照片,并将它们与ForeignKey链接在一起(不确定是否正确,但仍在学习中)。 What I need is for the Album class's __unicode__ to return the album owner's username. 我需要的是Album类的__unicode__返回专辑所有者的用户名。

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. 我知道用户名属性存在,并通过插入dir()并检查控制台输出来确认它。 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? 模型不能访问User属性吗? Or am I doing something else wrong? 还是我做错了其他事?

EDIT: Forgot to mention, using Python 2.6 with Django 1.0.2. 编辑:忘了提一下,在Django 1.0.2中使用Python 2.6。 The exact text of the error is, as above, simply "Unrecognised command" in bold, and I've already run syncdb without issue. 如上所述,错误的确切文本只是粗体的“ Unrecognised command”,而且我已经运行了syncdb没有任何问题。 However, I reran syncdb (gave no output) this morning just to try again and now it seems to be working fine. 但是,今天早上我重新运行了syncdb (未输出),只是想再试一次,现在看来一切正常。

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'

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. 附带一提,您还应该只能返回self.artist,因为我相信User.__unicode__()仍然会返回用户名。

What are the exact details of the error? 错误的确切详细信息是什么? What version of Django/Python are you using? 您正在使用哪个版本的Django / Python? 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM