如果其活动状态已更改,则向Django用户发送电子邮件 [英] Send an email if to a Django User if their active status is changed

查看:65
本文介绍了如果其活动状态已更改,则向Django用户发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立了一个网站,该网站的某些部分需要会员资格.这是一个俱乐部网站,因此要成为该网站的成员,您必须成为现实生活中的成员.计划是让俱乐部中的某人检查新会员(我可能会让系统在用户注册时向他们发送电子邮件),然后管理员选中用户记录下的 active 复选框.在Django管理员中保存用户.

我要解决的问题是,我们需要通知新的有效用户何时可以开始使用其帐户.显然,手动发送电子邮件很麻烦.

有没有办法挂入 save()逻辑,检查记录的 active 状态是否已更改,如果已激活,则向该用户发送电子邮件告诉他们他们现在可以登录?

我在所有电子邮件逻辑之上,我只需要知道将其放置在何处即可.

我意识到还有其他测试方法(在cron样式的工作上,在 active == True 帐户上检查 last_login == None ),但是我想通知几乎是即时的.

解决方案

还可以再使用5年,但这在django 1.8和python 2.7下对我有效

上下文是:用户创建一个新帐户,然后管理员收到一封电子邮件以验证该用户,并在管理员进行更改时将活动更改为True,该用户收到一封电子邮件,告知他现在可以登录.

对不起,我的英语不好.

 #forms.py从Django导入表格从django.contrib.auth.forms导入UserCreationForm从django.contrib.auth.models导入用户#A将字段is_active保存为False的注册表类RegisterForm(UserCreationForm):电子邮件=表格.EmailField(label = _(电子邮件"))first_name = Forms.CharField(label = _(名字"))last_name = Forms.CharField(label = _(姓氏"))is_active = forms.BooleanField(必填= False,initial = False,label = _("Activo"),widget = forms.HiddenInput())类Meta:型号=用户字段=('用户名','名字_','姓氏','电子邮件','密码1','密码2','is_active')def save(self,commit = True):用户=超级(UserCreationForm,自我).保存(提交=假)user.first_name = self.cleaned_data ['first_name']user.last_name = self.cleaned_data ['last_name']user.email = self.cleaned_data ['email']user.is_active = self.cleaned_data ['is_active']如果提交:user.save()回头用户 

我在models.py文件中使用信号,但您可以在signals.py文件中使用

 #models.py从django.contrib.auth.models导入用户从django.db.models导入信号从django.db导入模型从django.dispatch导入接收器从django.db.models.signals导入pre_save,post_save从django.conf导入设置从django.core.mail导入send_mail用于is_active = False的is_active = True的#signal@receiver(pre_save,sender = User,dispatch_uid ='active')def active(发送方,实例,** kwargs):如果instance.is_active和User.objects.filter(pk = instance.pk,is_active = False).exists():主题=有效帐户"mesagge ='%s您的帐户现在处于活动状态'%(instance.username)from_email =设置.EMAIL_HOST_USERsend_mail(主题,消息,from_email,[instance.email],fail_silently = False)#signal在用户创建新帐户时向管理员发送电子邮件@receiver(post_save,sender = User,dispatch_uid ='register')def寄存器(发送者,实例,** kwargs):如果kwargs.get('created',False):subject ='%s帐户的验证'%(instance.username)mesagge ='将您的消息发送给管理员'from_email =设置.EMAIL_HOST_USERsend_mail(主题,消息,from_email,[from_email],fail_silently = False) 

I've built a site that requires membership for some portions. It's a club website so to be a member on the website, you have to be a member in real life. The plan is to have somebody from the Club check for new members (I'll probably have the system send them an email when a user signs up) and then the admin checks the active checkbox under the user's record in the Django admin and saves the user.

The problem I'm trying to overcome is we need new, valid users to be notified as to when they can start using their account. Obviously manually sending an email is cumbersome.

Is there a way to hook into the save() logic, check if the record's active state has changed, and if it has been activated, send that user an email telling them they can now log in?

I'm on top of all the email logic, I just need to know where to put it.

I realise there are other ways of testing (check for last_login==None on active==True accounts on a cron-style job) but I'd like notifications to be near-enough instant.

解决方案

ok 5 years latter but this works for me with django 1.8 and python 2.7

The context is: the user create a new account then the admin receives an email to verify the user and chage active to True when the admin makes the change the user receives an email telling that now he can log in.

Sorry for my bad english.

#forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

#A register form that save field is_active as False
class RegisterForm(UserCreationForm):
    email = forms.EmailField(label=_("E-mail"))
    first_name = forms.CharField(label=_("First Name"))
    last_name = forms.CharField(label=_("Last Name"))
    is_active = forms.BooleanField(required=False, initial=False, label=_("Activo"), widget=forms.HiddenInput())

    class Meta:
        model = User
        fields = ('username','first_name','last_name','email','password1','password2','is_active')

        def save(self, commit=True):
            user = super(UserCreationForm, self).save(commit=False)
            user.first_name = self.cleaned_data['first_name']
            user.last_name = self.cleaned_data['last_name']
            user.email = self.cleaned_data['email']
            user.is_active = self.cleaned_data['is_active']
            if commit:
                user.save()
            return user

I use the signals in models.py file but you can use it in a signals.py file

#models.py
from django.contrib.auth.models import User
from django.db.models import signals
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import pre_save, post_save
from django.conf import settings
from django.core.mail import send_mail

#signal used for is_active=False to is_active=True
@receiver(pre_save, sender=User, dispatch_uid='active')
def active(sender, instance, **kwargs):
    if instance.is_active and User.objects.filter(pk=instance.pk, is_active=False).exists():
        subject = 'Active account'
        mesagge = '%s your account is now active' %(instance.username)
        from_email = settings.EMAIL_HOST_USER
        send_mail(subject, mesagge, from_email, [instance.email], fail_silently=False)

#signal to send an email to the admin when a user creates a new account
@receiver(post_save, sender=User, dispatch_uid='register')
def register(sender, instance, **kwargs):
    if kwargs.get('created', False):
        subject = 'Verificatión of the %s account' %(instance.username)
        mesagge = 'here goes your message to the admin'
        from_email = settings.EMAIL_HOST_USER
        send_mail(subject, mesagge, from_email, [from_email], fail_silently=False)

这篇关于如果其活动状态已更改,则向Django用户发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆