You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The free, open-source DjangoAdminGeomap library is designed to display objects on the map in the Django admin site.
7
+
The free, open-source DjangoAdminGeomap library is designed to display objects on the map in the Django views and admin site.
8
8
9
9

10
10
@@ -58,11 +58,11 @@ class Location(models.Model):
58
58
59
59
```
60
60
61
-
When working with this table in the admin panel, we want to see a map with objects from this table located on it.
61
+
On the main page of the site and when working with this table in the admin panel, we want to see a map with objects from this table located on it.
62
62
63
-
## Displaying a list of objects on the map
63
+
## Main page with a list of objects on the map
64
64
65
-
To enable the display of `Location` objects on the map in the Django admin panel, you need to make changes to the model class in the` models.py` file and to the `admin.py` file.
65
+
To enable the display of `Location` objects on the map, you need to make changes to the model class in the`models.py` file.
66
66
67
67
Add the `django_admin_geomap.GeoItem` "mixin" class to the inheritance list of the `Location` class and define two properties:` geomap_longitude` and `geomap_latitude`.
68
68
These properties should return the longitude and latitude of the object as a string.
@@ -76,14 +76,60 @@ class Location(models.Model, GeoItem):
76
76
77
77
@property
78
78
defgeomap_longitude(self):
79
-
returnstr(self.lon)
79
+
return''ifself.lon isNoneelsestr(self.lon)
80
80
81
81
@property
82
82
defgeomap_latitude(self):
83
-
returnstr(self.lat)
83
+
return''ifself.lon isNoneelsestr(self.lat)
84
84
```
85
85
86
-
In the `admin.py` file, when registering a model, you need to use the `django_admin_geomap.ModelAdmin` class.
86
+
After making these changes to the definition of the model, you can display a map with objects from the `Location` table in an arbitrary view.
87
+
To do this, you need to include the file `geomap/common.html` in the page template. For example, the site root page template `home.html` might look like this:
88
+
89
+
```html
90
+
<!DOCTYPE html>
91
+
<htmllang="en">
92
+
93
+
<head>
94
+
<title>DjangoAdminGeomap example</title>
95
+
</head>
96
+
97
+
<body>
98
+
Hello, OpenStreetMap!
99
+
<div>{% include "geomap/common.html" %}</div>
100
+
</body>
101
+
102
+
</html>
103
+
```
104
+
105
+
In the view function, you need to pass to this template the context formed by calling the `geomap_context` function.
106
+
As a required argument to the function, you need to pass an iterable sequence of objects to display on the map.
On the root page of the site, a map with markers in the locations of these objects will be displayed.
122
+
123
+
The `geomap_context` function accepts additional named arguments to customize the properties of the map.
124
+
125
+
- map_longitude: map center longitude, default is "0.0"
126
+
- map_latitude: map center latitude, default is "0.0"
127
+
- map_zoom: map zoom level, default is "1"
128
+
- map_height: vertical map size, default is "500px"
129
+
130
+
## List of objects on the map in the admin panel
131
+
132
+
To display a map with objects in the site admin panel in the admin settings file `admin.py`, when registering a model, you need to use the` django_admin_geomap.ModelAdmin` class.
After making these changes, in the admin panel on the page with a list of `Location` objects, a map with markers at the locations of these objects will be displayed under the table.
98
144
99
-
## Displaying the object on the map in the edit form
145
+
## Displaying the object on the map in the edit form in the admin panel
100
146
101
147
To display an object on the map in the edit/view form, you must additionally specify the field IDs in the Django form, which contain the longitude and latitude values of the object.
102
148
@@ -145,10 +191,13 @@ class Location(models.Model, GeoItem):
145
191
146
192
### Text in a pop-up block when you click on a marker on the map
147
193
148
-
The properties `geomap_popup_view` and `geomap_popup_edit` for the model class set the HTML code that is used in the pop-up block when the mouse is clicked on the marker on the map.
149
-
The `geomap_popup_view` property specifies the code for a user without permission to edit the object, and the` geomap_popup_edit` property - for a user who has permission to edit.
194
+
When you click on a marker on the map, a pop-up panel is displayed. The HTML code used in this panel can be set by defining three properties on the model class.
195
+
196
+
-`geomap_popup_common` displayed in regular views
197
+
-`geomap_popup_view` displayed in the admin panel for a user without permission to edit the object
198
+
-`geomap_popup_edit` displayed in the admin panel for a user who has permission to edit
150
199
151
-
By default, both properties return the string representation of the object.
200
+
By default, all these properties return the string representation of the object.
152
201
153
202
```python
154
203
# models.py
@@ -164,11 +213,15 @@ class Location(models.Model, GeoItem):
164
213
@property
165
214
defgeomap_popup_edit(self):
166
215
returnself.geomap_popup_view
216
+
217
+
@property
218
+
defgeomap_popup_common(self):
219
+
returnself.geomap_popup_view
167
220
```
168
221
169
222
### New object icon
170
223
171
-
The `geomap_new_feature_icon` property of the `django_admin_geomap.ModelAdmin` class sets the path to the marker icon when adding a new object.
224
+
The `geomap_new_feature_icon` property of the `django_admin_geomap.ModelAdmin` class sets the path to the marker icon when adding a new object in the admin panel.
172
225
173
226
```python
174
227
# admin.py
@@ -178,7 +231,7 @@ class Admin(ModelAdmin):
178
231
geomap_new_feature_icon ="/myicon.png"
179
232
```
180
233
181
-
### Default map zoom level and center of the map when displaying a list of objects
234
+
### Default map zoom level and center of the map when displaying a list of objects in the admin panel
182
235
183
236
You can change the zoom level and position of the center of the map by setting the properties `geomap_default_longitude`,` geomap_default_latitude` and `geomap_default_zoom` in the class `django_admin_geomap.ModelAdmin`.
184
237
@@ -194,7 +247,7 @@ class Admin(ModelAdmin):
194
247
geomap_default_zoom ="3"
195
248
```
196
249
197
-
### Default map zoom level when editing/viewing an object
250
+
### Default map zoom level when editing/viewing an object in the admin panel
198
251
199
252
In object edit form the center of the map coincides with the location of the object. The zoom level of the map can be set by using the `geomap_item_zoom` property of the `django_admin_geomap.ModelAdmin` class.
200
253
@@ -208,7 +261,7 @@ class Admin(ModelAdmin):
208
261
geomap_item_zoom ="10"
209
262
```
210
263
211
-
### Vertical map size
264
+
### Vertical map size in the admin panel
212
265
213
266
When displayed, the map occupies the maximum possible horizontal size. The vertical size can be set via the `geomap_height` property of the `django_admin_geomap.ModelAdmin` class.
214
267
The value must be a string valid in the CSS style definition.
Copy file name to clipboardExpand all lines: READMEru.md
+68-15Lines changed: 68 additions & 15 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,6 @@
1
1
# Библиотека DjangoAdminGeomap
2
2
3
-
Бесплатная, с открытым исходным кодом библиотека DjangoAdminGeomap предназначена для отображения объектов на карте в админке Django.
3
+
Бесплатная, с открытым исходным кодом библиотека DjangoAdminGeomap предназначена для отображения объектов на карте в представлениях (views) и админке Django.
4
4
5
5

6
6
@@ -54,11 +54,11 @@ class Location(models.Model):
54
54
55
55
```
56
56
57
-
При работе с этой таблицей в админке мы хотим видеть карту с расположенными на ней объектами из этой таблицы.
57
+
На главной странице сайта и при работе с этой таблицей в админке мы хотим видеть карту с расположенными на ней объектами из этой таблицы.
58
58
59
-
## Отображение списка объектов на карте
59
+
## Главная страница со списком объектов на карте
60
60
61
-
Чтобы включить отображение объектов `Location` на карте в админке Django нужно внести изменения в класс модели в файле `models.py` и в файл настроек админки `admin.py`.
61
+
Чтобы включить отображение объектов `Location` на карте нужно внести изменения в класс модели в файле `models.py`.
62
62
63
63
В список наследования класса `Location` нужно добавить "примесный" класс `django_admin_geomap.GeoItem` и определить два свойства: `geomap_longitude` и `geomap_latitude`.
64
64
Эти свойства должны возвращать долготу и широту объекта в виде строки.
@@ -72,14 +72,60 @@ class Location(models.Model, GeoItem):
72
72
73
73
@property
74
74
defgeomap_longitude(self):
75
-
returnstr(self.lon)
75
+
return''ifself.lon isNoneelsestr(self.lon)
76
76
77
77
@property
78
78
defgeomap_latitude(self):
79
-
returnstr(self.lat)
79
+
return''ifself.lon isNoneelsestr(self.lat)
80
80
```
81
81
82
-
В файле `admin.py` при регистрации модели нужно использовать класс `django_admin_geomap.ModelAdmin`.
82
+
После внесения данных изменений в определение модели можно отображать карту с объектами из таблицы `Location` в произвольном представлении (view).
83
+
Для этого в шаблон станицы нужно включить файл `geomap/common.html`. Например, шаблон корневой страницы сайта `home.html` может выглядеть так:
84
+
85
+
```html
86
+
<!DOCTYPE html>
87
+
<htmllang="en">
88
+
89
+
<head>
90
+
<title>DjangoAdminGeomap example</title>
91
+
</head>
92
+
93
+
<body>
94
+
Hello, OpenStreetMap!
95
+
<div>{% include "geomap/common.html" %}</div>
96
+
</body>
97
+
98
+
</html>
99
+
```
100
+
101
+
В функции представления нужно передавать в этот шаблон контекст, сформированный вызовом функции `geomap_context`.
102
+
В качестве обязательного аргумента функции нужно передать итерируемую последовательность объектов для отображения на карте.
На корневой странице сайта будет отображаться карта с маркерами в местах расположения этих объектов.
118
+
119
+
Функция `geomap_context` принимает дополнительные именованные аргументы, позволяющие настроить свойства карты.
120
+
121
+
- map_longitude: долгота центра карты, по умолчанию "0.0"
122
+
- map_latitude: широта центра карты, по умолчанию "0.0"
123
+
- map_zoom: масштаб карты, по умолчанию "1"
124
+
- map_height: размер карты по вертикали, по умолчанию "500px"
125
+
126
+
## Cписок объектов на карте в админке
127
+
128
+
Для отображения карты с обьектами в админке сайта в файле настроек админки `admin.py` при регистрации модели нужно использовать класс `django_admin_geomap.ModelAdmin`.
После внесения данных изменений в админке на странице со списком объектов `Location` под таблицей будет отображаться карта с маркерами в местах расположения этих объектов.
94
140
95
-
## Отображение редактируемого объекта на карте
141
+
## Отображение редактируемого объекта на карте в админке
96
142
97
143
Для отображения на карте объекта в форме редактирования/просмотра необходимо дополнительно указать идентификаторы полей в форме Django, в которых находятся значения долготы и широты объекта.
98
144
@@ -141,10 +187,13 @@ class Location(models.Model, GeoItem):
141
187
142
188
### Текст во всплывающем блоке при клике мышью по маркеру на карте
143
189
144
-
Свойства `geomap_popup_view` и `geomap_popup_edit` у класса модели задают HTML код, который используется во всплывающем блоке при клике мышью по маркеру на карте.
145
-
Свойство `geomap_popup_view` задает код для пользователя без прав на изменение объекта, а свойство `geomap_popup_edit` - для пользователя, который имеет права на редактирование.
190
+
При клике мышью по маркеру на карте отображается всплывающем блоке. Используемый в этом блоке HTML код можно задать, определив три свойства у класса модели.
191
+
192
+
-`geomap_popup_common` отображается в регулярных представлениях (views)
193
+
-`geomap_popup_view` отображается в админке для пользователя без прав на изменение объекта
194
+
-`geomap_popup_edit` отображается в админке для пользователя, который имеет права на редактирование
146
195
147
-
По умолчанию оба свойства возвращают строковое представление объекта.
196
+
По умолчанию все свойства возвращают строковое представление объекта.
148
197
149
198
```python
150
199
# models.py
@@ -160,11 +209,15 @@ class Location(models.Model, GeoItem):
160
209
@property
161
210
defgeomap_popup_edit(self):
162
211
returnself.geomap_popup_view
212
+
213
+
@property
214
+
defgeomap_popup_common(self):
215
+
returnself.geomap_popup_view
163
216
```
164
217
165
218
### Значок маркера нового объекта
166
219
167
-
Свойство `geomap_new_feature_icon` класса `django_admin_geomap.ModelAdmin` задает путь на значок маркера при добавлении нового объекта.
220
+
Свойство `geomap_new_feature_icon` класса `django_admin_geomap.ModelAdmin` задает путь на значок маркера при добавлении нового объекта в админке Django.
168
221
169
222
По умолчанию используется значок для отображения объектов на карте.
170
223
@@ -176,7 +229,7 @@ class Admin(ModelAdmin):
176
229
geomap_new_feature_icon ="/myicon.png"
177
230
```
178
231
179
-
### Масштаб и центр карты при отображении списка объектов
232
+
### Масштаб и центр карты при отображении списка объектов в админке
180
233
181
234
Вы можете менять масштаб и положение центра карты, задавая свойства `geomap_default_longitude`, `geomap_default_latitude` и `geomap_default_zoom` у класса `django_admin_geomap.ModelAdmin`.
182
235
@@ -192,7 +245,7 @@ class Admin(ModelAdmin):
192
245
geomap_default_zoom ="3"
193
246
```
194
247
195
-
### Масштаб карты при редактировании/просмотре объекта
248
+
### Масштаб карты при редактировании/просмотре объекта в админке
196
249
197
250
При редактировании/просмотре объекта центр карты совпадает с местом расположения объекта, а масштаб карты можно задать, используя свойство `geomap_item_zoom` у класса `django_admin_geomap.ModelAdmin`.
198
251
@@ -206,7 +259,7 @@ class Admin(ModelAdmin):
206
259
geomap_item_zoom ="10"
207
260
```
208
261
209
-
### Размер карты по вертикали
262
+
### Размер карты по вертикали в админке
210
263
211
264
При отображении карта занимает максимально возможный размер по горизонтали, а размер по вертикали можно задать через свойство `geomap_height` у класса `django_admin_geomap.ModelAdmin`.
212
265
Значение должно быть строкой, допустимой в определении CSS стиля.
0 commit comments