我增加了系统离开“通知”中有关可能他们登录。我在models.py文件中创建一个简单的通知类的下一次显示的用户。我有这样的UserInfo类(在相同models.py)到某些属性Django的现有用户系统添加为socialauth的一部分:

class UserInfo(models.Model):
    user = models.OneToOneField(User, unique=True)
    ...
    reputation = models.IntegerField(null=True, blank=True)

    def add_notification(message):
        notification = Notification(user=self.user, message=message)
        notification.save

当我尝试从控制台我结束了这样的:

>>> user = User.objects.get(id=14)
>>> user.userinfo.add_notification('you are an awesome intern!')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: add_notification() takes exactly 1 argument (2 given)
>>> 

我缺少的是在这里吗?我是那种一个Django小白所以也许它的东西很容易。谢谢!

有帮助吗?

解决方案

使用Django消息

首先,请考虑 dcrodjer的回答。 Django的信息系统正是你需要什么,以及为什么把你的代码树的东西,你得到免费的吗?

(当然,如果你这样做只是为了尝试和了解更多关于Django的,请继续!)


反正修复

总结:为了解决这个问题,只是改变add_notifications这样:

    def add_notification(self, message):
        notification = Notification(user=self.user, message=message)
        notification.save

请注意在该方法中的签名附加参数(名为self)。


为什么它不工作

有有点中的异常行为的在调用Python方法。

class Foo(object):
    def bar(self):
        print 'Calling bar'

    def baz(self, shrubbery):
        print 'Calling baz'

thisguy = Foo()

当调用方法bar,可以使用像thisguy.bar()的线。 Python看到你调用一个对象(被称为上的对象称为bar thisguy法)上的一个方法。当发生这种情况,Python的填充与该对象自身(thisguy对象)的方法的第一个参数。

你的方法不起作用的原因是,你在一个方法只期待一个参数调用userinfo.add_notification('you are an awesome intern!')。好吧,巨蟒已经填补了第一个参数(名为message)与userinfo对象。因此,Python的抱怨说你传递两个参数到仅期望一个的方法。

其他提示

使用django的消息框架: http://docs.djangoproject.com/en/dev/ REF /了contrib /消息/ 结果 你可以把用户信息存储的消息队列中,当他在使用这个记录:

messages.add_message(request, messages.INFO, 'Hello world.')

add_notification是一个类的方法。这意味着它含蓄地被传递的类的实例作为第一个参数。在Python

尝试这个代替:

class UserInfo(models.Model):
    ...
    def add_notification(self, message):
        ...

您或许应该,如果你正在寻找持久的消息更新您的问题。也许 https://github.com/philomat/django-persistent-messages 可以帮助你节省编码时间?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top