【问题标题】:Control a function (E.g send mail) from a users profile page从用户个人资料页面控制功能(例如发送邮件)
【发布时间】:2011-04-27 09:27:11
【问题描述】:

我有一个像这样的个人资料页面:http://i.stack.imgur.com/Rx4kg.png。在管理中,我想要一个“通过邮件通知”选项,它可以控制我想要的每个应用程序中的 send_email 功能。例如,我正在使用 django-messages,它会在您发送消息时发送私人消息以及电子邮件。我希望用户能够在收到消息时指定他是否还想要电子邮件。

消息/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 模板更改它们?如果这是正确的方法,一些细节和想法会很有帮助!

【问题讨论】:

    标签: django django-models django-forms django-views


    【解决方案1】:

    您可能希望从creating a user profile 开始,这样您就有一种存储天气的好方法,或者用户是否希望将这些电子邮件发送给他们。这是使用settings.py 中的AUTH_PROFILE_MODULE 设置完成的。

    一旦您存储了数据,您应该能够从instance.recipient 访问它(假设instance.recipient 是一个User 对象)。因此,您可以将代码更改为:

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

    做完了。

    【讨论】:

    • 确实完成了!在我的个人资料中添加了一个 BooleanField(),并且能够完全按照描述使用它,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 2018-04-14
    • 2015-10-06
    相关资源
    最近更新 更多