title: How to use CORS in django rest framework?
body: <p>I have used <code>django-cors-headers</code> for <code>CORS</code> but unable to get <code>CORS</code> to work in a right way.</p>
  <p>Like from client end I can run code from any host that are not in ALLOWED HOSTS but the request still completes without any <code>CORS</code> error.</p>
  <p>Can anyone tell me , how can I only allow whitelisted hosts?</p>
  <p>My <code>settings.py</code></p>
  <pre><code>from pathlib import Path
  import os
  
  # Build paths inside the project like this: BASE_DIR / 'subdir'.
  BASE_DIR = Path(__file__).resolve().parent.parent
  
  
  # Quick-start development settings - unsuitable for production
  # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
  
  # SECURITY WARNING: keep the secret key used in production secret!
  SECRET_KEY = os.environ[&quot;SECRET_KEY&quot;]
  
  # SECURITY WARNING: don't run with debug turned on in production!
  
  SECURITY_TRUE = True
  SECURITY_FALSE = False
  
  DEBUG = False
  
  CSRF_COOKIE_SECURE = True
  
  SESSION_COOKIE_SECURE = True
  
  SECURE_SSL_REDIRECT = True
  
  SECURE_HSTS_INCLUDE_SUBDOMAINS = True
  
  SECURE_HSTS_PRELOAD = True
  
  SECURE_HSTS_SECONDS = 1 #31536000
  
  ALLOWED_HOSTS = [&quot;127.0.0.1&quot;] 
  
  # Application definition
  
  INSTALLED_APPS = [
      'django.contrib.admin',
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.messages',
      'django.contrib.staticfiles',
      # add rest_framework support to the project
      'rest_framework',
      # setting cors policy is needed to make calls from ui to api
      'corsheaders',
      'mauth'
  ]
  
  MIDDLEWARE = [
      # Add cors middleware
      'corsheaders.middleware.CorsMiddleware',
      'django.middleware.security.SecurityMiddleware',
      'whitenoise.middleware.WhiteNoiseMiddleware',
      'django.contrib.sessions.middleware.SessionMiddleware',
      'django.middleware.common.CommonMiddleware',
      'django.middleware.csrf.CsrfViewMiddleware',
      'django.contrib.auth.middleware.AuthenticationMiddleware',
      'django.contrib.messages.middleware.MessageMiddleware',
      'django.middleware.clickjacking.XFrameOptionsMiddleware',
  ]
  
  ROOT_URLCONF = 'm.urls'
  
  TEMPLATES = [
      {
          'BACKEND': 'django.template.backends.django.DjangoTemplates',
          'DIRS': [os.path.join(BASE_DIR, &quot;frontend&quot;)],
          'APP_DIRS': True,
          'OPTIONS': {
              'context_processors': [
                  'django.template.context_processors.debug',
                  'django.template.context_processors.request',
                  'django.contrib.auth.context_processors.auth',
                  'django.contrib.messages.context_processors.messages',
              ],
          },
      },
  ]
  
  WSGI_APPLICATION = 'm.wsgi.application'
  
  
  # Database
  # https://docs.djangoproject.com/en/3.2/ref/settings/#databases
  
  &quot;&quot;&quot;DATABASES = {
      'default': {
          'ENGINE': 'django.db.backends.sqlite3',
          'NAME': BASE_DIR / 'db.sqlite3',
      }
  }&quot;&quot;&quot;
  
  
  DATABASES = {
      'default': {
          'ENGINE': 'django.db.backends.postgresql',
          'NAME': os.environ[&quot;POSTGRES_NAME&quot;],
          'USER': os.environ[&quot;POSTGRES_USER&quot;],
          'PASSWORD': os.environ[&quot;POSTGRES_PASSWORD&quot;],
          'HOST': os.environ[&quot;POSTGRES_HOST&quot;],
          'PORT': os.environ[&quot;POSTGRES_PORT&quot;],
      }
  }
  
  # Password validation
  # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
  
  AUTH_PASSWORD_VALIDATORS = [
      {
          'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
      },
      {
          'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
      },
      {
          'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
      },
      {
          'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
      },
  ]
  
  
  # Internationalization
  # https://docs.djangoproject.com/en/3.2/topics/i18n/
  
  LANGUAGE_CODE = 'en-us'
  
  TIME_ZONE = 'UTC'
  
  USE_I18N = True
  
  USE_L10N = True
  
  USE_TZ = True
  
  
  # Static files (CSS, JavaScript, Images)
  # https://docs.djangoproject.com/en/3.2/howto/static-files/
  
  STATIC_URL = '/static/'
  
  STATICFILES_DIRS = [
    # Tell Django where to look for React's static files (css, js)
    os.path.join(BASE_DIR, &quot;frontend/static&quot;),
  ]
  
  STATIC_ROOT = os.path.join(BASE_DIR, &quot;static/&quot;)
  
  STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
  
  # Default primary key field type
  # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
  
  DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
  
  
  CORS_ORIGIN_ALLOW_ALL = False
  
  CORS_ALLOW_CREDENTIALS = True
  
  CORS_ALLOWED_ORIGINS = [
      'http://127.0.0.1',
  ]
  
  CORS_ALLOW_METHODS = (
      'DELETE',
      'GET',
      'OPTIONS',
      'PATCH',
      'POST',
      'PUT',
  )
  
  CORS_ALLOW_HEADERS = (
      'accept',
      'accept-encoding',
      'authorization',
      'content-type',
      'dnt',
      'origin',
      'user-agent',
      'x-csrftoken',
      'x-requested-with',
  )
  
  REST_FRAMEWORK = {
      'DEFAULT_AUTHENTICATION_CLASSES': [
          'mauth.authentication.JWTAuthentication',
      ],
      'DEFAULT_PERMISSION_CLASSES': [
          'rest_framework.permissions.IsAuthenticated',
      ]
  }
  </code></pre>
  <p>For frontend I'm using:</p>
  <pre><code>  config[&quot;headers&quot;][&quot;Access-Control-Allow-Origin&quot;] = ENV.API_URL
    config[&quot;headers&quot;][&quot;Access-Control-Allow-Credentials&quot;] = 'true'
  
  fetch(ENV.API_URL+url, config)
  </code></pre>