• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

makinacorpus / django-leaflet / 4859215502

pending completion
4859215502

push

github

Gagaro
Add support for Django 4.2

1 of 1 new or added line in 1 file covered. (100.0%)

409 of 491 relevant lines covered (83.3%)

13.33 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

80.23
/leaflet/__init__.py
1
from collections import OrderedDict
16✔
2
from urllib.parse import urlparse
16✔
3

4
import django
16✔
5
from django.conf import settings
16✔
6
from django.core.exceptions import ImproperlyConfigured
16✔
7
from django.templatetags.static import static
16✔
8
from django.utils.translation import gettext_lazy as _
16✔
9
from django.utils.functional import lazy, Promise
16✔
10

11
DEFAULT_TILES = [(_('OSM'), '//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
16✔
12
                  '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors')]
13

14
LEAFLET_CONFIG = getattr(settings, 'LEAFLET_CONFIG', {})
16✔
15
app_settings = dict({
16✔
16
    'TILES': DEFAULT_TILES,
17
    'OVERLAYS': [],
18
    'ATTRIBUTION_PREFIX': None,
19
    'LOADEVENT': 'load',
20
    'DEFAULT_ZOOM': None,
21
    'MIN_ZOOM': None,
22
    'MAX_ZOOM': None,
23
    'DEFAULT_CENTER': None,
24
    'DEFAULT_PRECISION': 6,
25
    'FORCE_IMAGE_PATH': False,
26
    'SRID': None,
27
    'TILES_EXTENT': [],
28
    'SCALE': 'metric',
29
    'MINIMAP': False,
30
    'RESET_VIEW': True,
31
    'NO_GLOBALS': True,
32
    'PLUGINS': OrderedDict(),
33
    'SPATIAL_EXTENT': (-180, -90, 180, 90),
34
}, **LEAFLET_CONFIG)
35

36

37
# If TILES is a string, convert to tuple
38
if isinstance(app_settings.get('TILES'), str):
16✔
39
    app_settings['TILES'] = [(_('Background'), app_settings.get('TILES'), '')]
×
40

41

42
# Verify that scale setting is valid.  For backwards-compatibility, interpret 'True' as 'metric'.
43
SCALE = app_settings.get("SCALE", None)
16✔
44
if SCALE is True:
16✔
45
    app_settings["SCALE"] = 'metric'
×
46
elif SCALE not in ('metric', 'imperial', 'both', None, False):
16✔
47
    raise ImproperlyConfigured("LEAFLET_CONFIG['SCALE'] must be True, False, None, 'metric', 'imperial' or 'both'.")
×
48

49

50
SPATIAL_EXTENT = app_settings.get("SPATIAL_EXTENT")
16✔
51
if SPATIAL_EXTENT is not None and not isinstance(SPATIAL_EXTENT, (tuple, list)) or len(SPATIAL_EXTENT) != 4:
16✔
52
    raise ImproperlyConfigured(_("Spatial extent should be a tuple (minx, miny, maxx, maxy)"))
×
53

54

55
SRID = app_settings.get("SRID")
16✔
56
if SRID == 3857:  # Leaflet's default, do not setup custom projection machinery
16✔
57
    SRID = None
×
58

59

60
TILES_EXTENT = app_settings.get("TILES_EXTENT")
16✔
61
# Due to bug in Leaflet/Proj4Leaflet ()
62
# landscape extents are not supported.
63
if SRID and TILES_EXTENT and (TILES_EXTENT[2] - TILES_EXTENT[0] > TILES_EXTENT[3] - TILES_EXTENT[1]):
16✔
64
    raise ImproperlyConfigured('Landscape tiles extent not supported (%s).' % (TILES_EXTENT,))
×
65

66

67
DEFAULT_CENTER = app_settings['DEFAULT_CENTER']
16✔
68
if DEFAULT_CENTER is not None and not (isinstance(DEFAULT_CENTER, (list, tuple)) and len(DEFAULT_CENTER) == 2):
16✔
69
    raise ImproperlyConfigured("LEAFLET_CONFIG['DEFAULT_CENTER'] must be an list/tuple with two elements - (lat, lon)")
×
70

71

72
DEFAULT_ZOOM = app_settings['DEFAULT_ZOOM']
16✔
73
if DEFAULT_ZOOM is not None and not (isinstance(DEFAULT_ZOOM, int) and (1 <= DEFAULT_ZOOM <= 24)):
16✔
74
    raise ImproperlyConfigured("LEAFLET_CONFIG['DEFAULT_ZOOM'] must be an int between 1 and 24.")
×
75

76

77
DEFAULT_PRECISION = app_settings['DEFAULT_PRECISION']
16✔
78
if DEFAULT_PRECISION is not None and not (isinstance(DEFAULT_PRECISION, int) and (4 <= DEFAULT_PRECISION <= 12)):
16✔
79
    raise ImproperlyConfigured("LEAFLET_CONFIG['DEFAULT_PRECISION'] must be an int between 4 and 12.")
×
80

81

82
PLUGINS = app_settings['PLUGINS']
16✔
83
if not (isinstance(PLUGINS, dict) and all([isinstance(el, dict) for el in PLUGINS.values()])):
16✔
84
    error_msg = """LEAFLET_CONFIG['PLUGINS'] must be dict of dicts in the format:
×
85
    { '[plugin_name]': { 'js': '[path-to-js]', 'css': '[path-to-css]' } } .)"""
86
    raise ImproperlyConfigured(error_msg)
×
87

88
PLUGIN_ALL = 'ALL'
16✔
89
PLUGINS_DEFAULT = '__default__'
16✔
90
PLUGIN_FORMS = 'forms'
16✔
91

92
# Add plugins required for forms (not auto-included)
93
# Assets will be preprended to any existing entry in PLUGINS['forms']
94
_forms_js = ['leaflet/draw/leaflet.draw.js',
16✔
95
             'leaflet/leaflet.extras.js',
96
             'leaflet/leaflet.forms.js']
97
if SRID:
16✔
98
    _forms_js += ['leaflet/proj4.js',
×
99
                  'leaflet/proj4leaflet.js',
100
                  'proj4js/%s.js' % SRID]
101

102
_forms_css = ['leaflet/draw/leaflet.draw.css']
16✔
103
_forms_plugins = PLUGINS.setdefault(PLUGIN_FORMS, {})
16✔
104
_forms_plugins['js'] = _forms_js + _forms_plugins.get('js', [])
16✔
105
_forms_plugins['css'] = _forms_css + _forms_plugins.get('css', [])
16✔
106
_forms_plugins.setdefault('auto-include', False)
16✔
107
PLUGINS[PLUGIN_FORMS] = _forms_plugins
16✔
108

109
# Take advantage of plugin system for Leaflet.MiniMap
110
if app_settings.get('MINIMAP'):
16✔
111
    PLUGINS['minimap'] = {
×
112
        'css': 'leaflet/Control.MiniMap.css',
113
        'js': 'leaflet/Control.MiniMap.js',
114
        'auto-include': True
115
    }
116

117

118
def _normalize_plugins_config():
16✔
119
    """
120
    Normalizes the PLUGINS setting:
121
        * ensures the 'css' and 'js' are arrays of URLs
122
        * ensures all URLs are transformed as follows:
123
            ** if the URL is absolute - leave it as-is
124
            ** if the URL is a root URL - starts with a / - leave it as-is
125
            ** the the URL is not a root URL - does not start with / - prepend settings.STATIC_URL
126
    Also, adds a special key - ALL - that includes 'css' and 'js' for all plugins listed
127
    """
128
    if '__is_normalized__' in PLUGINS:  # already normalized
16✔
129
        return
×
130

131
    listed_plugins = list(PLUGINS.keys())
16✔
132
    PLUGINS[PLUGINS_DEFAULT] = OrderedDict()
16✔
133
    PLUGINS[PLUGIN_ALL] = OrderedDict()
16✔
134

135
    RESOURCE_TYPE_KEYS = ['css', 'js']
16✔
136

137
    for key in listed_plugins:
16✔
138
        plugin_dict = PLUGINS[key]
16✔
139

140
        for resource_type in RESOURCE_TYPE_KEYS:
16✔
141
            # normalize the resource URLs
142
            urls = plugin_dict.get(resource_type, None)
16✔
143
            if isinstance(urls, str):
16✔
144
                urls = [urls]
16✔
145
            elif isinstance(urls, tuple):  # force to list
16✔
146
                urls = list(urls)
×
147
            elif isinstance(urls, list):  # already a list
16✔
148
                pass
16✔
149
            else:  # css/js has not been specified or the wrong type
150
                urls = []
16✔
151

152
            # normalize the URLs - see the docstring for details
153
            for i, url in enumerate(urls):
16✔
154
                if isinstance(url, Promise):
16✔
155
                    # If it is a Promise, then we have already
156
                    # seen this url and have lazily applied the `static` call
157
                    # to it, so we can safely skip the check below.
158
                    continue
16✔
159
                url_parts = urlparse(url)
16✔
160
                if url_parts.scheme or url_parts.path.startswith('/'):
16✔
161
                    # absolute URL or a URL starting at root
162
                    pass
×
163
                else:
164
                    # pass relative URL through django.contrib.staticfiles
165
                    urls[i] = lazy(static, str)(url)  # lazy variant of `static(url)`
16✔
166

167
            plugin_dict[resource_type] = urls
16✔
168

169
            # Append it to the DEFAULT pseudo-plugin if auto-include
170
            if plugin_dict.get('auto-include', False):
16✔
171
                PLUGINS[PLUGINS_DEFAULT].setdefault(resource_type, []).extend(urls)
16✔
172

173
            # also append it to the ALL pseudo-plugin;
174
            PLUGINS[PLUGIN_ALL].setdefault(resource_type, []).extend(urls)
16✔
175

176
    PLUGINS['__is_normalized__'] = True
16✔
177

178

179
if django.VERSION < (3, 2):
16✔
180
    default_app_config = 'leaflet.apps.LeafletConfig'
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc