gpt4 book ai didi

Django仅在 View 成功完成后才保存

转载 作者:行者123 更新时间:2023-12-02 21:40:25 24 4
gpt4 key购买 nike

我正在使用 Django 1.5.4,似乎它有这个调试设置,导致保存方法在 View 成功完成之前不会保存。这使得用户注册后立即登录的功能变得不可能。

我尝试设置DEBUG=False,但没有帮助。每个模型都会发生这种情况。我正在使用 MySQL,但我很确定那根本不相关。我正在使用电子邮件身份验证后端,如下:

from django.contrib.auth.models import User


class EmailBackend():
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None

def authenticate(self, username=None, password=None):
try:
user = User.objects.get(email=username)
except User.DoesNotExist:
return None

if user.check_password(password):
return user

我用来保存的代码很常见:

user = User()
user.first_name = full_name[0]
user.last_name = ' '.join(full_name[1:])
user.email = data['email']
user.username = create_username(user.first_name, user.last_name)
user.set_password(data['password'])
user.save()

auth_form = AuthenticationForm(data=request.POST or None)
if auth_form.is_valid():
login(request, auth_form.get_user())

我还查找了 Django 文档的 1.5.4 版和专业版,但也没有找到任何内容。

现在,这里可能发生什么?

最佳答案

Django 会立即保存,但是当启用 TransactionMiddleware 时,事务仅在请求结束时提交。

https://docs.djangoproject.com/en/1.5/topics/db/transactions/#tying-transactions-to-http-requests

The recommended way to handle transactions in Web requests is to tie them to the request and response phases via Django’s TransactionMiddleware.

It works like this: When a request starts, Django starts a transaction. If the response is produced without problems, Django commits any pending transactions. If the view function produces an exception, Django rolls back any pending transactions.

To activate this feature, just add the TransactionMiddleware middleware to your MIDDLEWARE_CLASSES setting

您可以 commit manually或转autocommit打开整个 View :

from django.db import transaction

@transaction.autocommit
def viewfunc(request):
....

您还可以从 MIDDLEWARE_CLASSES 中删除 TransactionMiddleware,但我不建议这样做。

关于Django仅在 View 成功完成后才保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20545508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com