2010-11-19 54 views
5

我正在添加一個系統爲下次登錄時可以顯示的用戶留下「通知」。我在models.py文件中創建了一個簡單的Notification類。我有這樣的UserInfo類(在同一個models.py)對某些屬性Django的現有用戶系統添加爲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 

當我嘗試它在我結束了這個控制檯:

>>> 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 noob,所以也許這很簡單。謝謝!

回答

7

使用Django消息

首先,請考慮dcrodjer's answer。 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!')一個只期待一個參數的方法。那麼,Python已經用userinfo對象填充了第一個參數(名爲message)。因此,Python抱怨你將兩個參數傳遞給只有預期的方法。

7

使用Django的消息框架:http://docs.djangoproject.com/en/dev/ref/contrib/messages/
你可能只要他在使用這個記錄把用戶信息在隊列中存儲的消息:

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

我期待有一個通知系統,通知會一直持續到用戶通過ajax調用關閉爲止,有點像Stack Overflow。你認爲消息可以做到這一點嗎? – gohnjanotis 2010-11-19 23:01:23

+0

是的...我猜消息是一個非常不錯的功能...我也使用它...你應該考慮[這個答案](http://stackoverflow.com/questions/4229044/create-user-notification-system -in-django的/ 4229263#4229263)。 – crodjer 2010-11-20 04:47:53

2

add_notification是一個類的方法。這意味着它隱式地通過類的實例作爲第一個參數。Classes in Python

試試這個:

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