【发布时间】:2015-09-01 21:45:06
【问题描述】:
上下文:
- 模型对象的 user_account_granted 帐户指示模型对象是否链接到非空用户帐户。
- 当 user_account_granted 从 False 变为 True 时,我在覆盖的 save() 函数中检测到这一点。在这里,我成功创建了一个用户,从模型对象中提取参数(电子邮件、用户名、姓名等)
- 我创建一个密码并将新帐户登录信息发送到对象的电子邮件
- 如果邮件失败,我会删除帐户
问题:
我想提醒当前用户(刚刚提交了触发 save() 的表单)电子邮件成功(并且新帐户现在存在)或不成功(并且没有创建新帐户)。我不能在 save() 函数中使用 Django 消息传递框架,因为它需要请求。我能做什么?
def save(self, *args, **kwargs):
if self.id:
previous_fields = MyModel(pk=self.id)
if previous_fields.user_account_granted != self.user_account_granted:
title = "Here's your account!"
if previous_fields.user_account_granted == False and self.user_account_granted == True:
user = User(
username=self.first_name + "." + self.last_name,
email=self.email,
first_name=self.first_name,
last_name=self.last_name
)
random_password = User.objects.make_random_password() #this gets hashed on user create
user.set_password(random_password)
user.save()
self.user = user
message = "You have just been given an account! \n\n Here's your account info: \nemail: " + self.user.email + "\npassword: " + random_password
if previous_fields.user_account_granted == True and self.user_account_granted == False:
message = "You no longer have an account. Sorry :( "
try:
sent_success = send_mail(title, message, 'example@email.com', [self.email], fail_silently=False)
if sent_success == 1:
##HERE I WANT TO INDICATE EMAIL SENT SUCCESS TO THE USER'S VIEW AFTER THE FORM IS SUBMITTED
else:
##HERE I WANT TO INDICATE EMAIL SENT FAILURE TO THE USER'S VIEW AFTER THE FORM IS SUBMITTED
user.delete()
self.user_account_granted = False
except:
##HERE I WANT TO INDICATE EMAIL SENT FAILURE TO THE USER'S VIEW AFTER THE FORM IS SUBMITTED
user.delete()
self.user_account_granted = False
super(MyModel, self).save(*args, **kwargs)
【问题讨论】:
标签: python django model save message