我如何从 Django 模型的(重写的) save( ) 函数向视图发送警报或消息?

Cha*_*ngg 5 python django message model save

语境:

  1. 模型对象的 user_account_granted 帐户指示模型对象是否链接到非空用户帐户。
  2. 当 user_account_granted 从 False 更改为 True 时,我在重写的 save() 函数中检测到这一点。在这里,我成功创建了一个用户,从模型对象中提取参数(电子邮件、用户名、姓名等)
  3. 我创建一个密码并将新帐户登录信息发送到对象的电子邮件
  4. 如果电子邮件发送失败,我会删除该帐户

问题:

我想提醒当前用户(刚刚提交了触发 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)
Run Code Online (Sandbox Code Playgroud)

spe*_*ras 3

您不会在模特的邮箱中发送电子邮件save()函数中发送电子邮件。曾经。这不是它的目的。考虑:

\n\n
    \n
  • save()可以从 shell 调用。
  • \n
  • save()可以从项目中的任何位置调用。
  • \n
\n\n

该方法的目的save()保存对象。故事结局。

\n\n

现在。让我们回到你真正想要实现的目标。您正在处理用户提交的表单。这意味着您至少在这里处理其他事情:表单和视图。

\n\n

让我们仔细看看他们的目的是什么:

\n\n
    \n
  • Form的基本作用是封装数据输入和验证。它可以扩展以涵盖Command的全部角色。毕竟,它只是缺少一个execute()功能。

  • \n
  • 视图的基本作用是根据浏览器的请求(此处为表单的 POST)采取操作并触发结果的显示。

  • \n
\n\n

您可以选择其中之一。您可以在表单上有一个execute()方法,然后从您的视图中调用它。或者您可以让视图在检查表单后采取行动is_valid()。我个人会选择用于实际操作的形式,以及用于显示结果的视图。

\n\n

因此,在我看来,我会自定义调用的form_valid()方法execute()结果那是:

\n\n
class MyForm(Form):\n    # whatever you already have there\n    def clean(self):\n        # unrelated to your issue, but just reminding you\n        # this is the place you make sure everything is right\n        # This very method MUST raise an error if any input or any\n        # other condition already known at that point is not fulfilled.\n        if you_do_not_want_to_grand_an_account:\n            raise ValidationError(\'Account not granted, because.\')\n        return self.cleaned_data\n\n    def execute(self):\n        do_whatever()\n        needs_to_be_done()\n        if it_failed:\n            raise AnAppropriateError(_(\'Descriptive message\'))\n\nclass MyView(FormView):\n    form = MyForm\n    # your other view stuff here\n\n    def form_valid(self, form):\n        try:\n            form.execute()\n        except AnAppropriateError as err:\n            messages.add_message(self.request, messages.ERROR, err.message)\n        else:\n            messages.add_message(self.request, messages.INFO, _(\'It worked\'))\n
Run Code Online (Sandbox Code Playgroud)\n\n

AnAppropriateError可能只是RuntimeError如果您想要它快速而肮脏,但您应该定义自己的异常类。

\n\n

另外,您可能想execute()\xcc\x80 method with根据其内容来装饰 @transaction.atomic()`。

\n\n

最后一点,请记住您无法确定电子邮件是否确实已发送。即使存在一些错误,邮件系统也会接受电子邮件,这是很常见的。几天后,你只会知道它反弹的时候。

\n