django-cors-headers

  1. Install the django-cors-headers package using pip:
pip install django-cors-headers
  1. Add 'corsheaders' to the INSTALLED_APPS list in your Django project's settings:
INSTALLED_APPS = [
    # ...
    'corsheaders',
    # ...
]
  1. Add 'corsheaders.middleware.CorsMiddleware' to the MIDDLEWARE list in your settings:
MIDDLEWARE = [
    # ...
    'corsheaders.middleware.CorsMiddleware',
    # ...
]
  1. Configure CORS settings in your project's settings:
CORS_ALLOWED_ORIGINS = [
    # add the domains or IPs that are allowed to make cross-origin requests
    "http://localhost:3000",  # example: your frontend development server
    "https://yourproductiondomain.com",
    # ...
]

# Optional: Allow credentials (cookies, authentication headers) to be included in cross-origin requests
CORS_ALLOW_CREDENTIALS = True
  1. (Optional) Fine-tune CORS settings based on your requirements:
# Example: Allow specific HTTP methods
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

# Example: Allow specific headers in the cross-origin request
CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]

# Example: Set the maximum age (in seconds) for which the CORS preflight response is cached
CORS_PREFLIGHT_MAX_AGE = 3600
  1. Run migrations to apply the changes to your database:
python manage.py migrate
  1. Start your Django development server:
python manage.py runserver

Your Django application is now configured to handle Cross-Origin Resource Sharing (CORS) using the django-cors-headers package.