Skip to content

Commit ac58d8b

Browse files
authored
Support for regular Django views (#4)
* use template for root page in the example * geomap context in common views * Django regular views * README.md * fix twine
1 parent 9446af7 commit ac58d8b

File tree

13 files changed

+242
-58
lines changed

13 files changed

+242
-58
lines changed

.pylintrc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@ disable=print-statement,
131131
import-outside-toplevel,
132132
consider-using-with,
133133
deprecated-module,
134+
consider-using-f-string,
134135
too-few-public-methods
135136

136137
# Enable the message, report, category or checker with the given id(s). You can

.pypirc

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
[distutils]
2+
index-servers =
3+
pypi
4+
testpypi
5+
6+
[pypi]
7+
repository = https://upload.pypi.org/legacy/
8+
9+
[testpypi]
10+
repository = https://test.pypi.org/legacy/

README.md

Lines changed: 68 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
[![Codacy Badge](https://app.codacy.com/project/badge/Grade/d565c3a3d78e4e198f35688432a741eb)](https://www.codacy.com/gh/vb64/django.admin.geomap/dashboard?utm_source=github.com&utm_medium=referral&utm_content=vb64/django.admin.geomap&utm_campaign=Badge_Grade)
55
[![Codacy Badge](https://app.codacy.com/project/badge/Coverage/d565c3a3d78e4e198f35688432a741eb)](https://www.codacy.com/gh/vb64/django.admin.geomap/dashboard?utm_source=github.com&utm_medium=referral&utm_content=vb64/django.admin.geomap&utm_campaign=Badge_Coverage)
66

7-
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.
88

99
![objects on the map in the Django admin site](img/listchange.png)
1010

@@ -58,11 +58,11 @@ class Location(models.Model):
5858

5959
```
6060

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.
6262

63-
## Displaying a list of objects on the map
63+
## Main page with a list of objects on the map
6464

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.
6666

6767
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`.
6868
These properties should return the longitude and latitude of the object as a string.
@@ -76,14 +76,60 @@ class Location(models.Model, GeoItem):
7676

7777
@property
7878
def geomap_longitude(self):
79-
return str(self.lon)
79+
return '' if self.lon is None else str(self.lon)
8080

8181
@property
8282
def geomap_latitude(self):
83-
return str(self.lat)
83+
return '' if self.lon is None else str(self.lat)
8484
```
8585

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+
<html lang="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.
107+
For example a list or Django QuerySet.
108+
109+
```python
110+
# views.py
111+
from django.shortcuts import render
112+
from django_admin_geomap import geomap_context
113+
114+
from .models import Location
115+
116+
117+
def home(request):
118+
return render(request, 'home.html', geomap_context(Location.objects.all()))
119+
```
120+
121+
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.
87133

88134
```python
89135
# admin.py
@@ -96,7 +142,7 @@ admin.site.register(Location, ModelAdmin)
96142

97143
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.
98144

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
100146

101147
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.
102148

@@ -145,10 +191,13 @@ class Location(models.Model, GeoItem):
145191

146192
### Text in a pop-up block when you click on a marker on the map
147193

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
150199

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.
152201

153202
```python
154203
# models.py
@@ -164,11 +213,15 @@ class Location(models.Model, GeoItem):
164213
@property
165214
def geomap_popup_edit(self):
166215
return self.geomap_popup_view
216+
217+
@property
218+
def geomap_popup_common(self):
219+
return self.geomap_popup_view
167220
```
168221

169222
### New object icon
170223

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.
172225

173226
```python
174227
# admin.py
@@ -178,7 +231,7 @@ class Admin(ModelAdmin):
178231
geomap_new_feature_icon = "/myicon.png"
179232
```
180233

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
182235

183236
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`.
184237

@@ -194,7 +247,7 @@ class Admin(ModelAdmin):
194247
geomap_default_zoom = "3"
195248
```
196249

197-
### Default map zoom level when editing/viewing an object
250+
### Default map zoom level when editing/viewing an object in the admin panel
198251

199252
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.
200253

@@ -208,7 +261,7 @@ class Admin(ModelAdmin):
208261
geomap_item_zoom = "10"
209262
```
210263

211-
### Vertical map size
264+
### Vertical map size in the admin panel
212265

213266
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.
214267
The value must be a string valid in the CSS style definition.

READMEru.md

Lines changed: 68 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Библиотека DjangoAdminGeomap
22

3-
Бесплатная, с открытым исходным кодом библиотека DjangoAdminGeomap предназначена для отображения объектов на карте в админке Django.
3+
Бесплатная, с открытым исходным кодом библиотека DjangoAdminGeomap предназначена для отображения объектов на карте в представлениях (views) и админке Django.
44

55
![объекты на карте в админке Django](img/listchange01.jpg)
66

@@ -54,11 +54,11 @@ class Location(models.Model):
5454

5555
```
5656

57-
При работе с этой таблицей в админке мы хотим видеть карту с расположенными на ней объектами из этой таблицы.
57+
На главной странице сайта и при работе с этой таблицей в админке мы хотим видеть карту с расположенными на ней объектами из этой таблицы.
5858

59-
## Отображение списка объектов на карте
59+
## Главная страница со списком объектов на карте
6060

61-
Чтобы включить отображение объектов `Location` на карте в админке Django нужно внести изменения в класс модели в файле `models.py` и в файл настроек админки `admin.py`.
61+
Чтобы включить отображение объектов `Location` на карте нужно внести изменения в класс модели в файле `models.py`.
6262

6363
В список наследования класса `Location` нужно добавить "примесный" класс `django_admin_geomap.GeoItem` и определить два свойства: `geomap_longitude` и `geomap_latitude`.
6464
Эти свойства должны возвращать долготу и широту объекта в виде строки.
@@ -72,14 +72,60 @@ class Location(models.Model, GeoItem):
7272

7373
@property
7474
def geomap_longitude(self):
75-
return str(self.lon)
75+
return '' if self.lon is None else str(self.lon)
7676

7777
@property
7878
def geomap_latitude(self):
79-
return str(self.lat)
79+
return '' if self.lon is None else str(self.lat)
8080
```
8181

82-
В файле `admin.py` при регистрации модели нужно использовать класс `django_admin_geomap.ModelAdmin`.
82+
После внесения данных изменений в определение модели можно отображать карту с объектами из таблицы `Location` в произвольном представлении (view).
83+
Для этого в шаблон станицы нужно включить файл `geomap/common.html`. Например, шаблон корневой страницы сайта `home.html` может выглядеть так:
84+
85+
```html
86+
<!DOCTYPE html>
87+
<html lang="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+
В качестве обязательного аргумента функции нужно передать итерируемую последовательность объектов для отображения на карте.
103+
Например, список или Django QuerySet.
104+
105+
```python
106+
# views.py
107+
from django.shortcuts import render
108+
from django_admin_geomap import geomap_context
109+
110+
from .models import Location
111+
112+
113+
def home(request):
114+
return render(request, 'home.html', geomap_context(Location.objects.all()))
115+
```
116+
117+
На корневой странице сайта будет отображаться карта с маркерами в местах расположения этих объектов.
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`.
83129

84130
```python
85131
# admin.py
@@ -92,7 +138,7 @@ admin.site.register(Location, ModelAdmin)
92138

93139
После внесения данных изменений в админке на странице со списком объектов `Location` под таблицей будет отображаться карта с маркерами в местах расположения этих объектов.
94140

95-
## Отображение редактируемого объекта на карте
141+
## Отображение редактируемого объекта на карте в админке
96142

97143
Для отображения на карте объекта в форме редактирования/просмотра необходимо дополнительно указать идентификаторы полей в форме Django, в которых находятся значения долготы и широты объекта.
98144

@@ -141,10 +187,13 @@ class Location(models.Model, GeoItem):
141187

142188
### Текст во всплывающем блоке при клике мышью по маркеру на карте
143189

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` отображается в админке для пользователя, который имеет права на редактирование
146195

147-
По умолчанию оба свойства возвращают строковое представление объекта.
196+
По умолчанию все свойства возвращают строковое представление объекта.
148197

149198
```python
150199
# models.py
@@ -160,11 +209,15 @@ class Location(models.Model, GeoItem):
160209
@property
161210
def geomap_popup_edit(self):
162211
return self.geomap_popup_view
212+
213+
@property
214+
def geomap_popup_common(self):
215+
return self.geomap_popup_view
163216
```
164217

165218
### Значок маркера нового объекта
166219

167-
Свойство `geomap_new_feature_icon` класса `django_admin_geomap.ModelAdmin` задает путь на значок маркера при добавлении нового объекта.
220+
Свойство `geomap_new_feature_icon` класса `django_admin_geomap.ModelAdmin` задает путь на значок маркера при добавлении нового объекта в админке Django.
168221

169222
По умолчанию используется значок для отображения объектов на карте.
170223

@@ -176,7 +229,7 @@ class Admin(ModelAdmin):
176229
geomap_new_feature_icon = "/myicon.png"
177230
```
178231

179-
### Масштаб и центр карты при отображении списка объектов
232+
### Масштаб и центр карты при отображении списка объектов в админке
180233

181234
Вы можете менять масштаб и положение центра карты, задавая свойства `geomap_default_longitude`, `geomap_default_latitude` и `geomap_default_zoom` у класса `django_admin_geomap.ModelAdmin`.
182235

@@ -192,7 +245,7 @@ class Admin(ModelAdmin):
192245
geomap_default_zoom = "3"
193246
```
194247

195-
### Масштаб карты при редактировании/просмотре объекта
248+
### Масштаб карты при редактировании/просмотре объекта в админке
196249

197250
При редактировании/просмотре объекта центр карты совпадает с местом расположения объекта, а масштаб карты можно задать, используя свойство `geomap_item_zoom` у класса `django_admin_geomap.ModelAdmin`.
198251

@@ -206,7 +259,7 @@ class Admin(ModelAdmin):
206259
geomap_item_zoom = "10"
207260
```
208261

209-
### Размер карты по вертикали
262+
### Размер карты по вертикали в админке
210263

211264
При отображении карта занимает максимально возможный размер по горизонтали, а размер по вертикали можно задать через свойство `geomap_height` у класса `django_admin_geomap.ModelAdmin`.
212265
Значение должно быть строкой, допустимой в определении CSS стиля.

0 commit comments

Comments
 (0)