How to Enable CORS in Django

My Django learning app deployed on raspberrypi for kids was functioning smoothly when accessed from a home network. However, when we had to travel to Kolkata, and the app was promoted to a PythonAnywhere server. This move brought about a new challenge, as the app started to face issues with Cross-Origin Resource Sharing (CORS).

I soon realized that this was a common issue and could be easily resolved by enabling CORS in the Django app.

I followed the following simple process and soon had the app up and running smoothly again, with CORS enabled. The end.

Here’s how to enable CORS in Django:

  • Install the Django-Cors-Headers package by running python -m pip install Django-cors-headers
  • Add it to the INSTALLED_APPS list in your Django settings:
INSTALLED_APPS = [    ...    'corsheaders',    ...]
  • Add the CorsMiddleware class to the MIDDLEWARE list:
MIDDLEWARE = [    ...,    'corsheaders.middleware.CorsMiddleware',    'django.middleware.common.CommonMiddleware',    ...,]
  • Configure the CORS headers by setting the following variables in your Django settings:
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
    'http://localhost:1234',
]
CORS_ALLOWED_ORIGIN_REGEXES = [
    'http://localhost:1234',
]

Note: CORS_ALLOW_ALL_ORIGINS set to True allows all origins, while CORS_ALLOWED_ORIGINS only allows specific origins listed in the list.

And so, the journey with the Django app continued without any further hiccups and kids are still using the same for their spaced revision and review.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s