[英]Does form_valid on a CreateView in django roll back a save if an error occurs?
I have a CreateView for a ModelForm with a form_valid() method, which calls form.save() quite early on (so that I can get the object's ID), then goes on to do some other stuff (create some related objects, and send some emails). 我有一个带有form_valid()方法的ModelForm的CreateView,它很早就调用了form.save()(这样我就可以获得对象的ID),然后继续做其他一些事情(创建一些相关的对象,以及发一些电子邮件)。
def form_valid(self, form):
context = self.get_context_data()
preferences_formset = context['preferences_formset']
if preferences_formset.is_valid():
student = form.save()
...
send_email_one()
send_email_two()
send_email_three()
return HttpResponseRedirect(self.get_success_url())
I recently discovered that some of the later processing had some errors resulting in an unhandled exception in some cases when send_email_three is called. 我最近发现,在调用send_email_three时,某些后续处理有一些错误导致未处理的异常。 I can see from my logs that send_email_one and send_email_two are being called, and the exception occurs in send_email_three.
我可以从我的日志中看到正在调用send_email_one和send_email_two,并且send_email_three中发生异常。 However, when this has occurred, I can't find the objects in the DB.
但是,当发生这种情况时,我无法在DB中找到对象。 I was under the impression that form.save() should create and save the object in the DB - is this the case or does it roll back the save if the form_valid function errors out at a later point?
我的印象是form.save()应该创建并保存数据库中的对象 - 是这种情况还是如果form_valid函数稍后出错则回滚保存?
I'm using django 1.8.17 我正在使用django 1.8.17
PS: Yes, I know I should have the emails in a deferred task; PS:是的,我知道我应该在推迟的任务中收到电子邮件; that will be implemented later.
这将在以后实施。
That depends on the ATOMIC_REQUESTS
setting. 这取决于
ATOMIC_REQUESTS
设置。 Setting it to True
will trigger the behaviour described in the docs : 将其设置为
True
将触发文档中描述的行为:
Before calling a view function, Django starts a transaction.
在调用视图函数之前,Django启动一个事务。 If the response is produced without problems, Django commits the transaction.
如果生成的响应没有问题,Django会提交事务。 If the view produces an exception, Django rolls back the transaction.
如果视图产生异常,Django将回滚事务。
You can use @transaction.atomic
decorator 你可以使用
@transaction.atomic
decorator
https://docs.djangoproject.com/en/1.10/topics/db/transactions/#controlling-transactions-explicitly https://docs.djangoproject.com/en/1.10/topics/db/transactions/#controlling-transactions-explicitly
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.