0

I try to create module with OpenStreetMaps on my website, but when I try use it i got some errors:

Access to image at 'https://c.tile.openstreetmap.org/3/6/5.png' (redirected from 'http://c.tile.openstreetmap.org/3/6/5.png') from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I try some method from web, but still not results. Can you see any error in code? In website script map is loading but map image have error. I try add corsheader middleware but problem still exist. I don't what to do more to repair this problem. All is fine but images have problem.

Settings file

from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
ALLOWED_HOSTS=['127.0.0.1']   

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '--'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True



# Application definition

INSTALLED_APPS = [
    'corsheaders',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'gosgucompl',
    
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'corsheaders.middleware.CorsPostCsrfMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    
]
CORS_ORIGIN_ALLOW_ALL = True

ROOT_URLCONF = 'gosgu.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'gosgu.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

#DATABASES = {
#    'default': {
#        'ENGINE': 'django.db.backends.sqlite3',
#        'NAME': BASE_DIR / 'db.sqlite3',
#    }
#}

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'gosgu',
        'USER': 'postgres',
        'PASSWORD': '###',
        'HOST': 'localhost',
        'PORT': '',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.0/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/4.0/topics/i18n/

LANGUAGE_CODE = 'pl-pl'

TIME_ZONE = 'Europe/Warsaw'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

html map file

{% extends 'gosgucompl/base.html' %}
{% block content %}

<div id="SGUGOMAP" style="height: 100%; width:100%; z-index: -2;"></div>

{% endblock %}

{% block scripts %}

    map = new OpenLayers.Map("SGUGOMAP",{zoomDuration: 1,projection: 'EPSG:4326',controls: []});
    map.addControl(new OpenLayers.Control.Navigation());
    map.addControl(new OpenLayers.Control.ArgParser());
    map.addControl(new OpenLayers.Control.Attribution());
    map.addLayer(new OpenLayers.Layer.OSM());
    map.zoomToMaxExtent();
    
    var pos = new OpenLayers.LonLat(50.323795, 18.927316);
    var markers = new OpenLayers.Layer.Markers("TEST");
    map.addLayer(markers);
    markers.addMarker(new OpenLayers.Marker(pos));

{% endblock %}
Jester48
  • 33
  • 7
  • you can try to add ```ALLOWED_HOSTS=['*'] CORS_ORIGIN_ALLOW_ALL = True ``` to the settings – LSeu Mar 24 '22 at 08:52
  • still not work ;/ – Jester48 Mar 24 '22 at 08:53
  • are you using a REST Framework ? – LSeu Mar 24 '22 at 08:53
  • No i not use rest framework – Jester48 Mar 24 '22 at 08:55
  • can you try to add a specify domains for CORS something like ```CORS_ALLOWED_ORIGINS = [ 'http://localhost:3030',]``` – LSeu Mar 24 '22 at 08:59
  • otherwise you will have to take a look at [cors configuration](https://github.com/adamchainz/django-cors-headers#configuration) paying particular attention to the various ```CORS_ORIGIN_``` settings. You'll need to set some of those based on your needs. – LSeu Mar 24 '22 at 09:01
  • 1
    You don't need to set CORS on _your_ application the error is for the site `https://c.tile.openstreetmap.org/3/6/5.png` i.e. that website needs to enable CORS. Although some testing implies it already is CORS enabled. The real problem is probably that you are calling that endpoint from HTTP and the site is using HTTPS. – Abdul Aziz Barkat Mar 24 '22 at 09:17
  • Does this answer your question? [Chrome CORS error on request to localhost dev server from remote site](https://stackoverflow.com/questions/66534759/chrome-cors-error-on-request-to-localhost-dev-server-from-remote-site) Also see [Why does my http://localhost CORS origin not work?](https://stackoverflow.com/questions/10883211/why-does-my-http-localhost-cors-origin-not-work) there are some browser extensions you could try out. – Abdul Aziz Barkat Mar 24 '22 at 09:17

1 Answers1

0

As Abdul Aziz Barkat says, it is not a django problem, but an OSM one: the resource you are trying to load (e.g. http://c.tile.openstreetmap.org/3/6/5.png) does not have the appropriate headers.

I had the same problem and ended up using the default GeoModelAdmin model, which uses OpenLayers.

PS: In django 4.0 OSMGeoAdmin is deprecated in favor of GISModelAdmin:

class OSMGeoAdmin: A subclass of GeoModelAdmin that uses a Spherical Mercator projection with OpenStreetMap street data tiles. Deprecated since version 4.0: This class is deprecated. Use GISModelAdmin instead.

Saigesp
  • 137
  • 1
  • 6