我在尝试保存Django User模型实例时遇到TransactionManagementError,并在其post_save信号中,我保存了一些将用户作为外键的模型.
在使用信号时,上下文和错误与此问题django TransactionManagementError非常相似
但是,在这种情况下,错误仅在单元测试时发生.
它在手动测试中运行良好,但单元测试失败.
有什么我想念的吗?
以下是代码段:
views.py
@csrf_exempt
def mobileRegister(request):
if request.method == 'GET':
response = {"error": "GET request not accepted!!"}
return HttpResponse(json.dumps(response), content_type="application/json",status=500)
elif request.method == 'POST':
postdata = json.loads(request.body)
try:
# Get POST data which is to be used to save the user
username = postdata.get('phone')
password = postdata.get('password')
email = postdata.get('email',"")
first_name = postdata.get('first_name',"")
last_name = postdata.get('last_name',"")
user = User(username=username, email=email,
first_name=first_name, last_name=last_name)
user._company = postdata.get('company',None)
user._country_code = postdata.get('country_code',"+91")
user.is_verified=True …Run Code Online (Sandbox Code Playgroud) 我的模特:
class UserProfile(models.Model):
TYPES_CHOICES = (
(0, _(u'teacher')),
(1, _(u'student')),
)
user = models.ForeignKey(User, unique=True)
type = models.SmallIntegerField(default=0, choices=TYPES_CHOICES, db_index=True)
cities = models.ManyToManyField(City)
class City(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50)
Run Code Online (Sandbox Code Playgroud)
在admin.py中:
admin.site.unregister(User)
class UserProfileInline(admin.StackedInline):
model = UserProfile
class UserProfileAdmin(UserAdmin):
inlines = [UserProfileInline]
admin.site.register(User, UserProfileAdmin)
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
"""Create a matching profile whenever a user object is created."""
if created:
profile, new = UserProfile.objects.get_or_create(user=instance)
Run Code Online (Sandbox Code Playgroud)
但是当我添加新用户并选择一个城市时,我得到了这个错误:/ admin/auth/user/add /中的IntegrityError(1062,"密钥'user_id'的重复条目'3'")
我的代码出了什么问题?如果我没有选择任何城市 - 用户被正确添加.某种程度上,用户被多次添加到UserProfile.