{"id":252,"hash":"269972dd262e250ba1dfac2da81dfc87ea621bfaa6069a4bcbb62e2328572a4e","pattern":"TransactionManagementError &quot;You can&#39;t execute queries until the end of the &#39;atomic&#39; block&quot; while using signals, but only during Unit Testing","full_message":"I am getting TransactionManagementError when trying to save a Django User model instance and in its post_save signal, I'm saving some models that have the user as the foreign key.\n\nThe context and error is pretty similar to this question\ndjango TransactionManagementError when using signals\n\nHowever, in this case, the error occurs only while unit testing.\n\nIt works well in manual testing, but unit tests fails.\n\nIs there anything that I'm missing?\n\nHere are the code snippets:\n\nviews.py\n\n@csrf_exempt\ndef mobileRegister(request):\n    if request.method == 'GET':\n        response = {\"error\": \"GET request not accepted!!\"}\n        return HttpResponse(json.dumps(response), content_type=\"application/json\",status=500)\n    elif request.method == 'POST':\n        postdata = json.loads(request.body)\n        try:\n            # Get POST data which is to be used to save the user\n            username = postdata.get('phone')\n            password = postdata.get('password')\n            email = postdata.get('email',\"\")\n            first_name = postdata.get('first_name',\"\")\n            last_name = postdata.get('last_name',\"\")\n            user = User(username=username, email=email,\n                        first_name=first_name, last_name=last_name)\n            user._company = postdata.get('company',None)\n            user._country_code = postdata.get('country_code',\"+91\")\n            user.is_verified=True\n            user._gcm_reg_id = postdata.get('reg_id',None)\n            user._gcm_device_id = postdata.get('device_id',None)\n            # Set Password for the user\n            user.set_password(password)\n            # Save the user\n            user.save()\n\nsignal.py\n\ndef create_user_profile(sender, instance, created, **kwargs):\n    if created:\n        company = None\n        companycontact = None\n        try:   # Try to make userprofile with company and country code provided\n            user = User.objects.get(id=instance.id)\n            rand_pass = random.randint(1000, 9999)\n            company = Company.objects.get_or_create(name=instance._company,user=user)\n            companycontact = CompanyContact.objects.get_or_create(contact_type=\"Owner\",company=company,contact_number=instance.username)\n            profile = UserProfile.objects.get_or_create(user=instance,phone=instance.username,verification_code=rand_pass,company=company,country_code=instance._country_code)\n            gcmDevice = GCMDevice.objects.create(registration_id=instance._gcm_reg_id,device_id=instance._gcm_reg_id,user=instance)\n        except Exception, e:\n            pass\n\ntests.py\n\nclass AuthTestCase(TestCase):\n    fixtures = ['nextgencatalogs/fixtures.json']\n    def setUp(self):\n        self.user_data={\n            \"phone\":\"0000000000\",\n            \"password\":\"123\",\n            \"first_name\":\"Gaurav\",\n            \"last_name\":\"Toshniwal\"\n            }\n\n    def test_registration_api_get(self):\n        response = self.client.get(\"/mobileRegister/\")\n        self.assertEqual(response.status_code,500)\n\n    def test_registration_api_post(self):\n        response = self.client.post(path=\"/mobileRegister/\",\n                                    data=json.dumps(self.user_data),\n                                    content_type=\"application/json\")\n        self.assertEqual(response.status_code,201)\n        self.user_data['username']=self.user_data['phone']\n        user = User.objects.get(username=self.user_data['username'])\n        # Check if the company was created\n        company = Company.objects.get(user__username=self.user_data['phone'])\n        self.assertIsInstance(company,Company)\n        # Check if the owner's contact is the same as the user's phone number\n        company_contact = CompanyContact.objects.get(company=company,contact_type=\"owner\")\n        self.assertEqual(user.username,company_contact[0].contact_number)\n\nTraceback:\n\n======================================================================\nERROR: test_registration_api_post (nextgencatalogs.apps.catalogsapp.tests.AuthTestCase)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n  File \"/Users/gauravtoshniwal1989/Developer/Web/Server/ngc/nextgencatalogs/apps/catalogsapp/tests.py\", line 29, in test_registration_api_post\n    user = User.objects.get(username=self.user_data['username'])\n  File \"/Users/gauravtoshniwal1989/Developer/Web/Server/ngc/ngcvenv/lib/python2.7/site-packages/django/db/models/manager.py\", line 151, in get\n    return self.get_queryset().get(*args, **kwargs)\n  File \"/Users/gauravtoshniwal1989/Developer/Web/Server/ngc/ngcvenv/lib/python2.7/site-packages/django/db/models/query.py\", line 301, in get\n    num = len(clone)\n  File \"/Users/gauravtoshniwal1989/Developer/Web/Server/ngc/ngcvenv/lib/python2.7/site-packages/django/db/models/query.py\", line 77, in __len__\n    self._fetch_all()\n  File \"/Users/gauravtoshniwal1989/Developer/Web/Server/ngc/ngcvenv/lib/python2.7/site-packages/django/db/models/query.py\", line 854, in _fetch_all\n    self._result_cache = list(self.iterator())\n  File \"/Users/gauravtoshniwal1989/Developer/Web/Server/ngc/ngcvenv/lib/python2.7/site-packages/django/db/models/query.py\", line 220, in iterator\n    for row in compiler.results_iter():\n  File \"/Users/gauravtoshniwal1989/Developer/Web/Server/ngc/ngcvenv/lib/python2.7/site-packages/django/db/models/sql/compiler.py\", line 710, in results_iter\n    for rows in self.execute_sql(MULTI):\n  File \"/Users/gauravtoshniwal1989/Developer/Web/Server/ngc/ngcvenv/lib/python2.7/site-packages/django/db/models/sql/compiler.py\", line 781, in execute_sql\n    cursor.execute(sql, params)\n  File \"/Users/gauravtoshniwal1989/Developer/Web/Server/ngc/ngcvenv/lib/python2.7/site-packages/django/db/backends/util.py\", line 47, in execute\n    self.db.validate_no_broken_transaction()\n  File \"/Users/gauravtoshniwal1989/Developer/Web/Server/ngc/ngcvenv/lib/python2.7/site-packages/django/db/backends/__init__.py\", line 365, in validate_no_broken_transaction\n    \"An error occurred in the curre","ecosystem":"pypi","package_name":"django","package_version":null,"solution":"I ran into this same problem myself. This is caused by a quirk in how transactions are handled in the newer versions of Django coupled with a unittest that intentionally triggers an exception.\n\nI had a unittest that checked to make sure a unique column constraint was enforced by purposefully triggering an IntegrityError exception:\n\ndef test_constraint(self):\n    try:\n        # Duplicates should be prevented.\n        models.Question.objects.create(domain=self.domain, slug='barks')\n        self.fail('Duplicate question allowed.')\n    except IntegrityError:\n        pass\n\n    do_more_model_stuff()\n\nIn Django 1.4, this works fine. However, in Django 1.5/1.6, each test is wrapped in a transaction, so if an exception occurs, it breaks the transaction until you explicitly roll it back. Therefore, any further ORM operations in that transaction, such as my do_more_model_stuff(), will fail with that django.db.transaction.TransactionManagementError exception.\n\nLike caio mentioned in the comments, the solution is to capture your exception with transaction.atomic like:\n\nfrom django.db import transaction\ndef test_constraint(self):\n    try:\n        # Duplicates should be prevented.\n        with transaction.atomic():\n            models.Question.objects.create(domain=self.domain, slug='barks')\n        self.fail('Duplicate question allowed.')\n    except IntegrityError:\n        pass\n\nThat will prevent the purposefully-thrown exception from breaking the entire unittest's transaction.","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/21458387/transactionmanagementerror-you-cant-execute-queries-until-the-end-of-the-atom","votes":289,"created_at":"2026-04-19T04:41:37.865340+00:00","updated_at":"2026-04-19T04:51:49.902595+00:00"}