2011-04-27 28 views
0

我有一個簡介頁面,如下所示:http://i.stack.imgur.com/Rx4kg.png。在管理中,我想要一個選項「通過郵件通知」來控制我想要的每個應用程序中的send_email函數。舉例來說,我使用的是django消息,當您發送消息時它會發送私人消息和電子郵件。我希望用戶能夠指定他是否需要電子郵件以及他收到郵件時。從用戶配置文件頁面控制功能(例如發送郵件)

消息/ utils.py

def new_message_email(sender, instance, signal, 
     subject_prefix=_(u'New Message: %(subject)s'), 
     template_name="messages/new_message.html", 
     default_protocol=None, 
     *args, **kwargs): 
    """ 
    This function sends an email and is called via Django's signal framework. 
    Optional arguments: 
     ``template_name``: the template to use 
     ``subject_prefix``: prefix for the email subject. 
     ``default_protocol``: default protocol in site URL passed to template 
    """ 
    if default_protocol is None: 
     default_protocol = getattr(settings, 'DEFAULT_HTTP_PROTOCOL', 'http') 

    if 'created' in kwargs and kwargs['created']: 
     try: 
      current_domain = Site.objects.get_current().domain 
      subject = subject_prefix % {'subject': instance.subject} 
      message = render_to_string(template_name, { 
       'site_url': '%s://%s' % (default_protocol, current_domain), 
       'message': instance, 
      }) 
      if instance.recipient.email != "": 
       send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, 
        [instance.recipient.email,]) 
     except Exception, e: 
      #print e 
      pass #fail silently 

顯然instance.recipient.email是接收用戶的電子郵件。所以我的問題是:如何在我的配置文件管理中創建一個可用於我的new_message_email的選項來檢查用戶是否需要電子郵件?我自己的想法是,我需要爲用戶在數據庫中保存一個值,然後在new_message_email函數中檢查該值。我怎麼做,但不明確。我是否在userprofile/views.py和userprofile/forms.py中的類中創建了一個新函數?並讓我的userprofile/overview.html模板改變它們?一些具體和想法,如果這是正確的方法將幫助很多!

回答

1

您可能想從creating a user profile開始,這樣您就可以很好地存儲天氣,或者用戶不希望將這些電子郵件發送給他們。這是通過使用settings.py中的AUTH_PROFILE_MODULE設置完成的。

存儲完數據後,您應該可以從instance.recipient訪問它(假設instance.recipientUser對象)。因此,您可以將您的代碼更改爲:

if instance.recipient.get_profile().wants_emails and instance.recipient.email != "": 
    send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, 
     [instance.recipient.email,]) 

完成並完成。

+0

的確做到了!在我的個人資料中添加了一個BooleanField(),並能夠完全按照描述使用它,謝謝! – leffe 2011-04-28 07:50:25