在Django中创建用户通知系统

goh*_*tis 9 django-models django-authentication django-socialauth

我正在添加一个系统,为下次登录时可以显示的用户留下"通知".我在models.py文件中创建了一个简单的Notification类.我有这个UserInfo类(在相同的models.py中)作为socialauth的一部分将一些属性添加到Django的现有用户系统:

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
Run Code Online (Sandbox Code Playgroud)

当我在控制台中尝试时,我最终得到了这个:

>>> 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)
>>> 
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?我是一个Django noob,所以也许这很简单.谢谢!

Wes*_*ley 11

使用Django消息

首先,请考虑dcrodjer的答案.Django消息系统正是您所需要的,为什么要在您的代码树中放入您免费获得的东西?

(当然,如果您这样做只是为了试验并了解有关Django的更多信息,请继续!)


无论如何,修复

简介:要解决此问题,只需更改add_notifications为:

    def add_notification(self, message):
        notification = Notification(user=self.user, message=message)
        notification.save
Run Code Online (Sandbox Code Playgroud)

请注意self方法签名中的附加参数(命名).


为什么它不起作用

在Python中调用方法有点怪癖.

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

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

thisguy = Foo()
Run Code Online (Sandbox Code Playgroud)

调用方法时bar,可以使用类似的行thisguy.bar().Python看到你调用一个对象(被称为方法上的一个方法bar在对象上调用thisguy).发生这种情况时,Python会使用对象本身(thisguy对象)填充方法的第一个参数.

你的方法不起作用的原因是你正在调用userinfo.add_notification('you are an awesome intern!')一个只期望一个参数的方法.好吧,Python已经messageuserinfo对象填充了第一个参数(命名).因此,Python抱怨你将两个参数传递给只需要一个的方法.


cro*_*jer 10

使用django消息框架:http: //docs.djangoproject.com/en/dev/ref/contrib/messages/
您可以在登录后立即将userinfo存储的消息放入队列:

messages.add_message(request, messages.INFO, 'Hello world.')
Run Code Online (Sandbox Code Playgroud)

  • 我希望有一个通知系统,其中通知会持续到用户通过ajax调用关闭它们,就像在Stack Overflow上一样.你认为消息可以做到这一点吗? (2认同)