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
Here's what each line means:
- File "/app/accounts/views.py", line 23, in register: The registration view calls create_user without first checking if the email already exists in the database.
- File "/venv/lib/python3.11/site-packages/django/contrib/auth/models.py", line 155, in _create_user: Django's UserManager._create_user calls save() which triggers the database INSERT.
- django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.email: The database rejected the INSERT because another row already has this email address.
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.
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})
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:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- 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:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- 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)
- Run the full test suite locally including duplicate email tests.
- Open a pull request with the form validation and error handling.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- 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.