How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Django · Python

Fix IntegrityError: UNIQUE constraint failed: accounts_user.email in Django

This error means a database insert or update tried to save a duplicate value in a column with a unique constraint. Fix it by validating uniqueness in the form or serializer before saving, using get_or_create() instead of create(), or handling the IntegrityError with a try/except block that returns a user-friendly error message.

Reading the Stack Trace

Traceback (most recent call last): File "/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 299, in _commit return self.connection.commit() File "/venv/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py", line 328, in commit return self.connection.commit() File "/venv/lib/python3.11/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/app/accounts/views.py", line 23, in register user = User.objects.create_user( File "/venv/lib/python3.11/site-packages/django/contrib/auth/models.py", line 161, in create_user return self._create_user(username, email, password, **extra_fields) File "/venv/lib/python3.11/site-packages/django/contrib/auth/models.py", line 155, in _create_user user.save(using=self._db) File "/venv/lib/python3.11/site-packages/django/db/models/base.py", line 814, in save self.save_base(using=using, force_insert=force_insert, force_update=force_update, update_fields=update_fields) django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.email

Here's what each line means:

Common Causes

1. No uniqueness check before create

The view calls create_user directly without first checking if a user with the same email already exists.

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                email=form.cleaned_data['email'],
                password=form.cleaned_data['password'],
            )
            return redirect('login')

2. Form missing unique validation

The registration form does not validate that the email is unique before submitting to the database.

class RegistrationForm(forms.Form):
    username = forms.CharField(max_length=150)
    email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput)
    # No clean_email method to check uniqueness

3. Race condition in concurrent requests

Two requests check for an existing email simultaneously, both find none, and both try to insert the same email.

def register(request):
    email = request.POST['email']
    if not User.objects.filter(email=email).exists():  # Race condition
        User.objects.create_user(email=email, ...)

The Fix

Add a clean_email method to the form that validates uniqueness before saving, and wrap create_user in a try/except IntegrityError as a safety net against race conditions. This provides a user-friendly error message instead of a 500 server error.

Before (broken)
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                email=form.cleaned_data['email'],
                password=form.cleaned_data['password'],
            )
            return redirect('login')
    else:
        form = RegistrationForm()
    return render(request, 'register.html', {'form': form})
After (fixed)
from django.db import IntegrityError

class RegistrationForm(forms.Form):
    username = forms.CharField(max_length=150)
    email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput)

    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError('A user with this email already exists.')
        return email

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            try:
                user = User.objects.create_user(
                    username=form.cleaned_data['username'],
                    email=form.cleaned_data['email'],
                    password=form.cleaned_data['password'],
                )
                return redirect('login')
            except IntegrityError:
                form.add_error('email', 'A user with this email already exists.')
    else:
        form = RegistrationForm()
    return render(request, 'register.html', {'form': form})

Testing the Fix

import pytest
from django.test import TestCase, Client
from django.contrib.auth.models import User


class TestRegistration(TestCase):
    def setUp(self):
        self.client = Client()
        User.objects.create_user('existing', email='taken@example.com', password='pass')

    def test_register_with_duplicate_email_shows_error(self):
        response = self.client.post('/register/', {
            'username': 'newuser',
            'email': 'taken@example.com',
            'password': 'securepass123',
        })
        assert response.status_code == 200
        self.assertContains(response, 'already exists')

    def test_register_with_unique_email_succeeds(self):
        response = self.client.post('/register/', {
            'username': 'newuser',
            'email': 'new@example.com',
            'password': 'securepass123',
        })
        assert response.status_code == 302
        assert User.objects.filter(email='new@example.com').exists()

    def test_form_clean_email_rejects_duplicate(self):
        from accounts.forms import RegistrationForm
        form = RegistrationForm(data={
            'username': 'another',
            'email': 'taken@example.com',
            'password': 'securepass123',
        })
        assert not form.is_valid()
        assert 'email' in form.errors

Run your tests:

pytest

Pushing Through CI/CD

git checkout -b fix/integrity-error-duplicate-email,git add accounts/views.py accounts/forms.py accounts/tests/,git commit -m "fix: validate email uniqueness before user creation",git push origin fix/integrity-error-duplicate-email

Your CI config should look something like this:

name: CI
on:
  pull_request:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_DB: test_db
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
        ports:
          - 5432:5432
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
          cache: 'pip'
      - run: pip install -r requirements.txt
      - run: pytest --tb=short -q

The Full Manual Process: 18 Steps

Here's every step you just went through to fix this one bug:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. Monitor production to confirm the error is resolved

Total time: 30-60 minutes. For one bug.

Or Let bugstack Fix It in Under 2 minutes

Every step above? bugstack does it automatically.

Step 1: Install the SDK

pip install bugstack

Step 2: Initialize

import bugstack

bugstack.init(api_key=os.environ["BUGSTACK_API_KEY"])

Step 3: There is no step 3.

bugstack handles everything from here:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. Deploys to production (or opens a PR for review)

Time from error to fix deployed: Under 2 minutes.

Human involvement: zero.

Try bugstack Free →

No credit card. 5-minute setup. Cancel anytime.

Deploying the Fix (Manual Path)

  1. Run the full test suite locally including duplicate email tests.
  2. Open a pull request with the form validation and error handling.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. Merge to main and verify registration works correctly in staging.

Frequently Asked Questions

BugStack runs the fix through your existing test suite, generates edge-case tests for duplicate and concurrent registrations, and validates that the form displays proper error messages before marking it safe to deploy.

BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.

Form validation catches duplicates for a good user experience, but a try/except on IntegrityError guards against race conditions where two requests pass validation simultaneously.

get_or_create is useful for idempotent operations, but for user registration you typically want to inform the user that the account already exists rather than silently returning the existing one.