Access-Control-Allow-Origin in Django app when accessed with Phonegap
Django by default does not provide the headers necessary to provide cross origin. The easiest way would be to just use this Django app that handles it for you: https://github.com/adamchainz/django-cors-headers
- Add to installed apps
- Add to middleware
- Then stuff like...
CORS_ALLOWED_ORIGINS = [ "http://read.only.com", "http://change.allowed.com",]
to support allowing all, just use the setting...CORS_ALLOW_ALL_ORIGINS = True
and then do any filtering of the request in middleware or in the view.
For single views you can manually add headers:
@require_GETdef api_getto(request): response = JsonResponse( # your stuff here ) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "GET, OPTIONS" response["Access-Control-Max-Age"] = "1000" response["Access-Control-Allow-Headers"] = "X-Requested-With, Content-Type" return response
You can use "django-cors-headers". Simply install it using pip:
pip install django-cors-headers
Add 'corsheaders' to your installed apps:
INSTALLED_APPS = [ ... 'corsheaders', ... ]
Add middleware:
MIDDLEWARE = [ ..., 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ..., ]
Then add this to your "settings.py":
CORS_ALLOWED_ORIGINS = [ 'http://siteyouwantto.allow.com', 'http://anothersite.allow.com', ]
If you also want to allow some domains to make "POST" requests, add this to your "settings.py" and don't forget to add it in "CORS_ALLOWED_ORIGINS".
CSRF_TRUSTED_ORIGINS = [ 'http://siteyouwantto.allow.com', ]
I hope this resolves your issue :)