Merge branch 'main' of https://git.cybercode.pro/sabron/mfssogr
3
.gitignore
vendored
@ -21,9 +21,10 @@ test*
|
||||
/.vscode
|
||||
.vscode
|
||||
.env
|
||||
.env
|
||||
test_data
|
||||
.idea
|
||||
docker-compose.yml
|
||||
media
|
||||
log
|
||||
png_and_tifs
|
||||
dxfs
|
||||
18
apps/gto/migrations/0015_alter_modeltypeicons_path.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 3.2.25 on 2025-05-15 09:22
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('gto', '0014_auto_20250121_1511'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='modeltypeicons',
|
||||
name='path',
|
||||
field=models.FileField(upload_to='map/gto'),
|
||||
),
|
||||
]
|
||||
18
apps/gto/migrations/0016_rename_path_modeltypeicons_icon.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 3.2.25 on 2025-05-15 09:22
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('gto', '0015_alter_modeltypeicons_path'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RenameField(
|
||||
model_name='modeltypeicons',
|
||||
old_name='path',
|
||||
new_name='icon',
|
||||
),
|
||||
]
|
||||
18
apps/gto/migrations/0017_alter_modeltypeicons_icon.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 3.2.25 on 2025-05-15 09:27
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('gto', '0016_rename_path_modeltypeicons_icon'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='modeltypeicons',
|
||||
name='icon',
|
||||
field=models.ImageField(upload_to='map/gto'),
|
||||
),
|
||||
]
|
||||
22
apps/gto/migrations/0018_auto_20250515_0933.py
Normal file
@ -0,0 +1,22 @@
|
||||
# Generated by Django 3.2.25 on 2025-05-15 09:33
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
def fix_icon_paths(apps, schema_editor):
|
||||
ModelTypeIcons = apps.get_model("gto", "ModelTypeIcons")
|
||||
for item in ModelTypeIcons.objects.all():
|
||||
if item.icon and 'media/' in item.icon.name:
|
||||
item.icon.name = item.icon.name.replace('media/', '')
|
||||
item.save()
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("gto", "0017_alter_modeltypeicons_icon"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(fix_icon_paths, reverse_code=migrations.RunPython.noop),
|
||||
]
|
||||
@ -3,11 +3,11 @@ from django.db import models
|
||||
|
||||
class ModelTypeIcons(models.Model):
|
||||
model = models.CharField(max_length=128)
|
||||
path = models.CharField(max_length=256)
|
||||
icon = models.ImageField(upload_to='map/gto') # Изменили на FileField
|
||||
|
||||
def __str__(self):
|
||||
return self.model
|
||||
|
||||
class Meta: # отображение в админики
|
||||
class Meta:
|
||||
verbose_name = "Иконка оборудования"
|
||||
verbose_name_plural = "Иконки оборудования"
|
||||
verbose_name_plural = "Иконки оборудования"
|
||||
@ -133,9 +133,6 @@
|
||||
<th>Наименование</th>
|
||||
<th>Государственный номер</th>
|
||||
<th>Время координат</th>
|
||||
<th>Широта</th>
|
||||
<th>Долгота</th>
|
||||
<th>Скорость</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@ -178,15 +175,6 @@
|
||||
<td>
|
||||
<a href="object/?id={{ catalog.id }}">{{ catalog.time }}</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="object/?id={{ catalog.id }}">{{ catalog.lat }}</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="object/?id={{ catalog.id }}">{{ catalog.lon }}</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="object/?id={{ catalog.id }}">{{ catalog.speed }}</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
@ -216,6 +204,7 @@
|
||||
|
||||
|
||||
|
||||
|
||||
{{ start_page_list_block|add:-1}}"
|
||||
aria-controls="mypaginator"
|
||||
data-dt-idx="
|
||||
@ -227,6 +216,7 @@
|
||||
|
||||
|
||||
|
||||
|
||||
{{ start_page_list_block|add:-1}}"
|
||||
style="padding: .3rem .5rem;"><span>..</span></a>
|
||||
</li>
|
||||
@ -265,6 +255,7 @@
|
||||
|
||||
|
||||
|
||||
|
||||
{{ end_page_list_block|add:1}}"
|
||||
aria-controls="mypaginator"
|
||||
data-dt-idx="
|
||||
@ -276,6 +267,7 @@
|
||||
|
||||
|
||||
|
||||
|
||||
{{ end_page_list_block|add:1}}"
|
||||
style="padding: .3rem .5rem;"><span>..</span></a>
|
||||
</li>
|
||||
@ -401,6 +393,34 @@
|
||||
<script src="{% static 'js/ol/map/map-layer-switcher.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/map/map-marker-manager.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/map/map-created-layer-manager.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script>
|
||||
function switchTab(tabHref) {
|
||||
// Находим элемент вкладки по href
|
||||
var tabElement = document.querySelector(`a[href="${tabHref}"]`);
|
||||
if (tabElement) {
|
||||
var tab = new bootstrap.Tab(tabElement);
|
||||
tab.show();
|
||||
|
||||
// Сохраняем выбранную вкладку в localStorage
|
||||
localStorage.setItem('gto_selectedTab', tabHref);
|
||||
} else {
|
||||
console.error('Вкладка с href ' + tabHref + ' не найдена.');
|
||||
}
|
||||
}
|
||||
|
||||
function restoreTab() {
|
||||
var gto_selectedTab = localStorage.getItem('gto_selectedTab');
|
||||
|
||||
if (gto_selectedTab) {
|
||||
switchTab(gto_selectedTab);
|
||||
}
|
||||
}
|
||||
|
||||
// Восстанавливаем вкладку при загрузке страницы
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
restoreTab();
|
||||
});
|
||||
</script>
|
||||
<script>
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
// Инициализация карты
|
||||
@ -420,38 +440,6 @@
|
||||
|
||||
mapCore.addLayer(gtoLayer, 'dynamic');
|
||||
|
||||
const scanLayer = new ol.layer.Tile({
|
||||
source: new ol.source.XYZ({
|
||||
url: `/media/map/orth/tiles/{z}/{x}/{y}.png?seed=${Math.random() * 1000}`,
|
||||
}),
|
||||
extent: ol.proj.transformExtent(
|
||||
[
|
||||
parseFloat('{{ orth_minLon }}'),
|
||||
parseFloat('{{ orth_minLat }}'),
|
||||
parseFloat('{{ orth_maxLon }}'),
|
||||
parseFloat('{{ orth_maxLat }}')
|
||||
],
|
||||
'EPSG:4326', // Исходная проекция
|
||||
'EPSG:3857' // Целевая проекция
|
||||
)
|
||||
});
|
||||
scanLayer.set('title', 'Ортофотоплан')
|
||||
scanLayer.set('name', 'orto')
|
||||
mapCore.addLayer(scanLayer)
|
||||
|
||||
const mineBorderLayer = new ol.layer.Vector({
|
||||
source: new ol.source.Vector({
|
||||
url: '/{{ prgr }}',
|
||||
format: new ol.format.KML({extractStyles: false}),
|
||||
|
||||
}),
|
||||
style: polygonStyleFunction,
|
||||
});
|
||||
mineBorderLayer.set('title', 'Границы ПРГР')
|
||||
mineBorderLayer.set('name', 'prgr')
|
||||
|
||||
mapCore.addLayer(mineBorderLayer)
|
||||
|
||||
// Инициализация статических слоев
|
||||
const createdLayersManager = new CreatedLayersManager({
|
||||
url: '{% url 'layers' %}',
|
||||
|
||||
@ -10,7 +10,6 @@ urlpatterns = [
|
||||
url(r"^object/$", views_main.object_edit, name="object_edit"),
|
||||
url(r"^object/block/$", views_main.object_block, name="object_block"),
|
||||
url(r"^object/sensor/$", views_main.sensor_edit, name="sensor_edit"),
|
||||
url(r"^object/sensor/sensor_ajax/$", views_main.sensor_ajax, name="sensor_ajax"),
|
||||
url(r"^update_object/$", views_main.update_object, name="update_object"),
|
||||
url(r"^reports/$", views_report.report_list, name="report_list"),
|
||||
url(r"^polygons/$", views_main.get_polygons, name="get_polygons"),
|
||||
|
||||
@ -1,19 +1,12 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import traceback
|
||||
import zoneinfo
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import requests
|
||||
from django import forms
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.core import exceptions
|
||||
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
|
||||
from django.db.models import Avg, Max, Min, Q
|
||||
from django.core.paginator import Paginator
|
||||
from django.db.models import Q
|
||||
from django.http import HttpResponse, JsonResponse
|
||||
from django.shortcuts import redirect, render
|
||||
from django.utils import timezone
|
||||
@ -43,7 +36,7 @@ def update_object(request):
|
||||
icon = ""
|
||||
icon_obj = ModelTypeIcons.objects.filter(model=type_g).first()
|
||||
if icon_obj is not None:
|
||||
icon = "/" + icon_obj.path
|
||||
icon = icon_obj.icon.url
|
||||
m_list.append(
|
||||
{
|
||||
"id": obj.id,
|
||||
@ -64,138 +57,6 @@ def update_object(request):
|
||||
except Exception as err:
|
||||
logging.error(traceback.format_exc())
|
||||
|
||||
|
||||
@login_required(login_url="/accounts/login/?next=")
|
||||
@never_cache
|
||||
def sensor_ajax(request):
|
||||
try:
|
||||
if request.method == "POST":
|
||||
sensor_dict = dict()
|
||||
param = request.POST.dict()
|
||||
sensor = Sensors.objects.filter(id=param["id"]).first()
|
||||
if sensor is None:
|
||||
m_sensor = []
|
||||
return generalmodule.ReturnJson(200, m_sensor)
|
||||
time = sensor.time
|
||||
value = sensor.value
|
||||
end_date = sensor.time + timedelta(seconds=15)
|
||||
|
||||
value_old = 0
|
||||
if param["sensor_type"] == "sec":
|
||||
strftime = "%d.%m.%Y %H:%M:%S"
|
||||
start_date = end_date - timedelta(seconds=30)
|
||||
sensor_links = (
|
||||
Indicators.objects.filter(sensor=sensor)
|
||||
.filter(time__range=[start_date, end_date - timedelta(seconds=15)])
|
||||
.order_by("time")
|
||||
.order_by("id")
|
||||
)
|
||||
if sensor_links.count() == 0:
|
||||
sensor_link = (
|
||||
AcsIndicators.objects.filter(sensor=sensor)
|
||||
.filter(time__lte=end_date)
|
||||
.order_by("-time")
|
||||
.first()
|
||||
)
|
||||
numsec = 31
|
||||
date_list = [
|
||||
sensor.time - timedelta(seconds=x) for x in range(numsec)
|
||||
]
|
||||
m_sensor = []
|
||||
for i in range(numsec):
|
||||
status = 0
|
||||
sensor_dict = dict()
|
||||
sensor_dict.update(date_max=str(time))
|
||||
sensor_dict.update(sn=sensor.id)
|
||||
sensor_dict.update(
|
||||
time=sensor.time.strftime("%d.%m.%Y %H:%M:%S")
|
||||
)
|
||||
sensor_dict.update(time=date_list[30 - i].strftime(strftime))
|
||||
sensor_dict.update(value=sensor_link.value)
|
||||
delta = (datetime.now() - sensor.time).total_seconds()
|
||||
if delta > 60:
|
||||
status = 1
|
||||
sensor_dict.update(status=status)
|
||||
m_sensor.append(sensor_dict)
|
||||
return generalmodule.ReturnJson(200, m_sensor)
|
||||
elif param["sensor_type"] == "min":
|
||||
strftime = "%d.%m.%Y %H:%M"
|
||||
start_date = end_date - timedelta(minutes=30)
|
||||
sensor_links = (
|
||||
Indicators.objects.filter(sensor=sensor)
|
||||
.filter(time__range=[start_date, end_date])
|
||||
.order_by("time")
|
||||
.order_by("id")
|
||||
)
|
||||
value_old = 0
|
||||
else:
|
||||
strftime = "%d.%m.%Y %H:00"
|
||||
start_date = end_date - timedelta(hours=30)
|
||||
sensor_links = (
|
||||
Indicators.objects.filter(sensor=sensor)
|
||||
.filter(time__range=[start_date, end_date])
|
||||
.order_by("time")
|
||||
.order_by("id")
|
||||
)
|
||||
value_old = 0
|
||||
strftimeend = "%d.%m.%Y %H"
|
||||
m_sensor = []
|
||||
for i in range(31):
|
||||
if param["sensor_type"] == "sec":
|
||||
strftimeend = "%d.%m.%Y %H:%M:%S"
|
||||
time = start_date + timedelta(seconds=i)
|
||||
start_date_day = time
|
||||
|
||||
end_date_day = time + timedelta(milliseconds=1000)
|
||||
elif param["sensor_type"] == "min":
|
||||
strftimeend = "%d.%m.%Y %H:%M"
|
||||
time = start_date + timedelta(minutes=i)
|
||||
start_date_day = datetime(
|
||||
time.year, time.month, time.day, time.hour, time.minute, 0
|
||||
)
|
||||
end_date_day = datetime(
|
||||
time.year,
|
||||
time.month,
|
||||
time.day,
|
||||
time.hour,
|
||||
time.minute,
|
||||
59,
|
||||
9999,
|
||||
)
|
||||
else:
|
||||
strftimeend = "%d.%m.%Y %H"
|
||||
time = start_date + timedelta(hours=i)
|
||||
start_date_day = datetime(
|
||||
time.year, time.month, time.day, time.hour, 0, 0
|
||||
)
|
||||
end_date_day = datetime(
|
||||
time.year, time.month, time.day, time.hour, 59, 59, 9999
|
||||
)
|
||||
status = 0
|
||||
sensor_dict = dict()
|
||||
sensor_dict.update(sn=sensor.id)
|
||||
sensor_dict.update(date_max=str(time))
|
||||
sensor_dict.update(time=sensor.time.strftime("%d.%m.%Y %H:%M:%S"))
|
||||
result = sensor_links.filter(
|
||||
time__range=[start_date_day, end_date_day]
|
||||
).aggregate(Max("value"))
|
||||
sensor_dict.update(time=time.strftime(strftime))
|
||||
if result["value__max"] == None:
|
||||
sensor_dict.update(value=sensor.value)
|
||||
else:
|
||||
value_old = result["value__max"]
|
||||
sensor_dict.update(value=result["value__max"])
|
||||
delta = (datetime.now() - sensor.time).total_seconds()
|
||||
if delta > 60:
|
||||
status = 1
|
||||
sensor_dict.update(status=status)
|
||||
m_sensor.append(sensor_dict)
|
||||
return generalmodule.ReturnJson(200, m_sensor)
|
||||
|
||||
except Exception as err:
|
||||
logging.error(traceback.format_exc())
|
||||
|
||||
|
||||
@login_required(login_url="/")
|
||||
@never_cache
|
||||
def sensor_edit(request):
|
||||
@ -312,7 +173,7 @@ def main_index(request):
|
||||
) # широта
|
||||
|
||||
param = request.GET.dict()
|
||||
date_start = datetime.now() - timedelta(days=1)
|
||||
date_start = datetime.now() - timedelta(days=7)
|
||||
my_filter = Q(block=False)
|
||||
my_filter &= Q(time__gte=date_start)
|
||||
clients = Equipment.objects.filter(my_filter).order_by("-time", "name").all()
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
import json
|
||||
|
||||
from django import forms
|
||||
from django.contrib import admin
|
||||
|
||||
from apps.main.models.model_dinamic_layer import DynamicLayer
|
||||
from apps.main.models.model_icons import Icons
|
||||
from apps.main.models.model_static_layer import StaticLayer
|
||||
|
||||
|
||||
@ -12,15 +12,16 @@ class PrettyJSONEncoder(json.JSONEncoder):
|
||||
super().__init__(*args, indent=2, sort_keys=True, **kwargs)
|
||||
|
||||
|
||||
class LayerModelForm(forms.ModelForm):
|
||||
layer_style = forms.JSONField(encoder=PrettyJSONEncoder)
|
||||
|
||||
|
||||
@admin.register(StaticLayer)
|
||||
class StaticLayerAdmin(admin.ModelAdmin):
|
||||
form = LayerModelForm
|
||||
pass
|
||||
|
||||
|
||||
@admin.register(DynamicLayer)
|
||||
class DynamicLayerAdmin(admin.ModelAdmin):
|
||||
form = LayerModelForm
|
||||
pass
|
||||
|
||||
|
||||
@admin.register(Icons)
|
||||
class IconsAdmin(admin.ModelAdmin):
|
||||
list_display = ('name', 'image')
|
||||
18
apps/main/migrations/0008_alter_staticlayer_layer_type.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 3.2.25 on 2025-05-13 02:49
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('main', '0007_auto_20250403_0750'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='staticlayer',
|
||||
name='layer_type',
|
||||
field=models.CharField(choices=[('Tile', 'Растровый'), ('Vector', 'Векторный')], default='Vector', max_length=50, verbose_name='Тип слоя'),
|
||||
),
|
||||
]
|
||||
17
apps/main/migrations/0009_remove_dynamiclayer_layer_style.py
Normal file
@ -0,0 +1,17 @@
|
||||
# Generated by Django 3.2.25 on 2025-05-13 02:59
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('main', '0008_alter_staticlayer_layer_type'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name='dynamiclayer',
|
||||
name='layer_style',
|
||||
),
|
||||
]
|
||||
33
apps/main/migrations/0010_auto_20250514_0214.py
Normal file
@ -0,0 +1,33 @@
|
||||
# Generated by Django 3.2.25 on 2025-05-14 02:14
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('main', '0009_remove_dynamiclayer_layer_style'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='staticlayer',
|
||||
name='max_lat',
|
||||
field=models.FloatField(blank=True, null=True, verbose_name='max_lat'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='staticlayer',
|
||||
name='max_lon',
|
||||
field=models.FloatField(blank=True, null=True, verbose_name='max_lon'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='staticlayer',
|
||||
name='min_lat',
|
||||
field=models.FloatField(blank=True, null=True, verbose_name='min_lat'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='staticlayer',
|
||||
name='min_lon',
|
||||
field=models.FloatField(blank=True, null=True, verbose_name='min_lon'),
|
||||
),
|
||||
]
|
||||
29
apps/main/migrations/0011_auto_20250515_0414.py
Normal file
@ -0,0 +1,29 @@
|
||||
# Generated by Django 3.2.25 on 2025-05-15 04:14
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('main', '0010_auto_20250514_0214'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Icons',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(max_length=128, verbose_name='Наименование')),
|
||||
('image', models.ImageField(upload_to='map/icons/', verbose_name='Изображение')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Иконка',
|
||||
'verbose_name_plural': 'Иконки',
|
||||
},
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='icons',
|
||||
index=models.Index(fields=['name'], name='main_icons_name_dec225_idx'),
|
||||
),
|
||||
]
|
||||
@ -11,7 +11,6 @@ class DynamicLayer(models.Model):
|
||||
url = models.CharField(max_length=255, verbose_name="URL данных")
|
||||
layer_type = models.CharField(max_length=50, verbose_name="Тип слоя")
|
||||
is_visible = models.BooleanField(default=True, verbose_name="Видимость слоя")
|
||||
layer_style = models.JSONField(blank=True, null=True)
|
||||
order = models.IntegerField(default=0, verbose_name="Порядок отображения")
|
||||
|
||||
def __str__(self):
|
||||
|
||||
16
apps/main/models/model_icons.py
Normal file
@ -0,0 +1,16 @@
|
||||
from django.db import models
|
||||
|
||||
|
||||
class Icons(models.Model):
|
||||
name = models.CharField(max_length=128, verbose_name="Наименование")
|
||||
image = models.ImageField(verbose_name="Изображение", upload_to="map/icons/")
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
class Meta:
|
||||
verbose_name = "Иконка"
|
||||
verbose_name_plural = "Иконки"
|
||||
indexes = [
|
||||
models.Index(fields=["name"])
|
||||
]
|
||||
@ -1,12 +1,17 @@
|
||||
import uuid
|
||||
import os
|
||||
import shutil
|
||||
import uuid
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
from django.db.models.signals import post_delete
|
||||
from django.dispatch import receiver
|
||||
|
||||
|
||||
def get_upload_path(instance, filename):
|
||||
ext = filename.split('.')[-1]
|
||||
ext = filename.split(".")[-1]
|
||||
new_filename = f"{uuid.uuid4()}.{ext}"
|
||||
return os.path.join('layers/', new_filename)
|
||||
return os.path.join("layers/", new_filename)
|
||||
|
||||
|
||||
def get_style_template() -> dict:
|
||||
@ -19,17 +24,25 @@ def get_style_template() -> dict:
|
||||
}
|
||||
|
||||
|
||||
orthos_path = os.path.join(settings.MEDIA_ROOT, "map", "orthos")
|
||||
if not os.path.exists(orthos_path):
|
||||
os.makedirs(orthos_path)
|
||||
|
||||
|
||||
class StaticLayer(models.Model):
|
||||
"""
|
||||
Модель слоев
|
||||
Типы слоев: Tile (плитки), Vector (точки, линии, полигоны)
|
||||
"""
|
||||
|
||||
LAYER_TYPES = (
|
||||
("Tile", "Растровый"),
|
||||
("Vector", "Векторный"),
|
||||
)
|
||||
|
||||
name = models.CharField(max_length=255, verbose_name="Название слоя")
|
||||
file = models.FileField(
|
||||
upload_to=get_upload_path,
|
||||
verbose_name="Файл слоя",
|
||||
null=True,
|
||||
upload_to=get_upload_path, verbose_name="Файл слоя", null=True,
|
||||
blank=True
|
||||
)
|
||||
url = models.CharField(
|
||||
@ -39,15 +52,32 @@ class StaticLayer(models.Model):
|
||||
verbose_name="Каталог (для растровых слоев)",
|
||||
)
|
||||
layer_type = models.CharField(
|
||||
max_length=50, verbose_name="Тип слоя", default="Vector"
|
||||
max_length=50, verbose_name="Тип слоя", default="Vector",
|
||||
choices=LAYER_TYPES
|
||||
)
|
||||
is_visible = models.BooleanField(default=True, verbose_name="Видимость слоя")
|
||||
is_visible = models.BooleanField(default=True,
|
||||
verbose_name="Видимость слоя")
|
||||
order = models.IntegerField(default=0, verbose_name="Порядок отображения")
|
||||
|
||||
min_lon = models.FloatField("min_lon", blank=True, null=True)
|
||||
min_lat = models.FloatField("min_lat", blank=True, null=True)
|
||||
max_lon = models.FloatField("max_lon", blank=True, null=True)
|
||||
max_lat = models.FloatField("max_lat", blank=True, null=True)
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
class Meta:
|
||||
verbose_name = "Статический слой"
|
||||
verbose_name_plural = "Статические слои"
|
||||
indexes = [models.Index(fields=["name"]), models.Index(fields=["is_visible"])]
|
||||
indexes = [models.Index(fields=["name"]),
|
||||
models.Index(fields=["is_visible"])]
|
||||
|
||||
|
||||
@receiver(post_delete, sender=StaticLayer)
|
||||
def remove_tiles(sender, instance, **kwargs):
|
||||
if hasattr(instance, "url"):
|
||||
path = instance.url
|
||||
rm_len = len(path) - 16
|
||||
rm_path = settings.MEDIA_ROOT + path[6:rm_len]
|
||||
shutil.rmtree(rm_path)
|
||||
|
||||
@ -345,7 +345,6 @@
|
||||
let translateInteraction = {}
|
||||
let extentInteraction = {}
|
||||
let i = 0
|
||||
const scanLayerExists = Boolean(parseInt('{{ scan_layer_enable }}'))
|
||||
let vectorSource = {}
|
||||
let vectorLayer = {}
|
||||
let group = {}
|
||||
@ -356,26 +355,6 @@
|
||||
}),
|
||||
]
|
||||
|
||||
if (scanLayerExists) {
|
||||
scanLayer = new ol.layer.Tile({
|
||||
source: new ol.source.XYZ({
|
||||
url: `/media/map/orth/tiles/{z}/{x}/{y}.png?seed=${Math.random() * 1000}`,
|
||||
}),
|
||||
extent: ol.proj.transformExtent(
|
||||
[
|
||||
parseFloat('{{ orth_minLon }}'),
|
||||
parseFloat('{{ orth_minLat }}'),
|
||||
parseFloat('{{ orth_maxLon }}'),
|
||||
parseFloat('{{ orth_maxLat }}')
|
||||
],
|
||||
'EPSG:4326', // Исходная проекция
|
||||
'EPSG:3857' // Целевая проекция
|
||||
)
|
||||
});
|
||||
scanLayer.set('name', 'Ортофотоплан')
|
||||
layers.push(scanLayer)
|
||||
}
|
||||
|
||||
function getCoordsByFeature(feature, resoluiton) {
|
||||
const coords = feature.getGeometry().getCoordinates()
|
||||
const coordsIn4326 = ol.proj.transform(coords, 'EPSG:3857', 'EPSG:4326');
|
||||
|
||||
@ -136,38 +136,6 @@
|
||||
mapCore.addLayer(workerLayer, 'dynamic');
|
||||
mapCore.addLayer(seismicLayer, 'dynamic');
|
||||
|
||||
const scanLayer = new ol.layer.Tile({
|
||||
source: new ol.source.XYZ({
|
||||
url: `/media/map/orth/tiles/{z}/{x}/{y}.png?seed=${Math.random() * 1000}`,
|
||||
}),
|
||||
extent: ol.proj.transformExtent(
|
||||
[
|
||||
parseFloat('{{ orth_minLon }}'),
|
||||
parseFloat('{{ orth_minLat }}'),
|
||||
parseFloat('{{ orth_maxLon }}'),
|
||||
parseFloat('{{ orth_maxLat }}')
|
||||
],
|
||||
'EPSG:4326', // Исходная проекция
|
||||
'EPSG:3857' // Целевая проекция
|
||||
)
|
||||
});
|
||||
scanLayer.set('title', 'Ортофотоплан')
|
||||
scanLayer.set('name', 'orto')
|
||||
mapCore.addLayer(scanLayer)
|
||||
|
||||
const mineBorderLayer = new ol.layer.Vector({
|
||||
source: new ol.source.Vector({
|
||||
url: '/{{ prgr }}',
|
||||
format: new ol.format.KML({extractStyles: false}),
|
||||
|
||||
}),
|
||||
style: polygonStyleFunction,
|
||||
});
|
||||
mineBorderLayer.set('title', 'Границы ПРГР')
|
||||
mineBorderLayer.set('name', 'prgr')
|
||||
|
||||
mapCore.addLayer(mineBorderLayer)
|
||||
|
||||
// Инициализация статических слоев
|
||||
const createdLayersManager = new CreatedLayersManager({
|
||||
url: '{% url 'layers' %}',
|
||||
|
||||
@ -8,8 +8,8 @@ from apps.main.views.views_layers import (create_layer, get_layers,
|
||||
from apps.main.views.views_main import get_coefficients
|
||||
|
||||
urlpatterns = [
|
||||
url(r"^$", views_main.mainindex, name="mainindex"),
|
||||
url(r"^coefficients/$", get_coefficients, name="get_coefficients"),
|
||||
path("", views_main.mainindex, name="mainindex"),
|
||||
path("coefficients/", get_coefficients, name="get_coefficients"),
|
||||
path("layers/", get_layers, name="layers"),
|
||||
path("create_layer/", create_layer, name="create_layer"),
|
||||
path("layers_list/", layers_list, name="layers_list"),
|
||||
|
||||
@ -13,19 +13,36 @@ from sabron.util import logging
|
||||
|
||||
|
||||
def get_layers(request):
|
||||
static_layers_qs = StaticLayer.objects.all()
|
||||
static_layers_qs = StaticLayer.objects.all().order_by("-order")
|
||||
res = {"static_layers": [], "dynamic_layers": []}
|
||||
for static_layer in static_layers_qs:
|
||||
if static_layer.file is None:
|
||||
if (static_layer.file is None and static_layer.layer_type == "Vector") or (static_layer.url is None and static_layer.layer_type == "Tile"):
|
||||
continue
|
||||
res["static_layers"].append(
|
||||
{
|
||||
"name": static_layer.name,
|
||||
"url": static_layer.file.url,
|
||||
"layer_type": static_layer.layer_type,
|
||||
"is_visible": static_layer.is_visible,
|
||||
}
|
||||
)
|
||||
|
||||
if static_layer.layer_type == "Vector":
|
||||
res["static_layers"].append(
|
||||
{
|
||||
"name": static_layer.name,
|
||||
"url": static_layer.file.url,
|
||||
"layer_type": static_layer.layer_type,
|
||||
"is_visible": static_layer.is_visible,
|
||||
}
|
||||
)
|
||||
elif static_layer.layer_type == "Tile":
|
||||
res["static_layers"].append(
|
||||
{
|
||||
"name": static_layer.name,
|
||||
"url": static_layer.url,
|
||||
"layer_type": static_layer.layer_type,
|
||||
"is_visible": static_layer.is_visible,
|
||||
"extent": [
|
||||
static_layer.min_lon,
|
||||
static_layer.min_lat,
|
||||
static_layer.max_lon,
|
||||
static_layer.max_lat,
|
||||
],
|
||||
}
|
||||
)
|
||||
dynamic_layers_qs = DynamicLayer.objects.all()
|
||||
for dynamic_layer in dynamic_layers_qs:
|
||||
res["dynamic_layers"].append(
|
||||
@ -70,7 +87,7 @@ def create_layer(request):
|
||||
def layers_list(request):
|
||||
try:
|
||||
context = generalmodule.get_context_template()
|
||||
static_layers = StaticLayer.objects.all()
|
||||
static_layers = StaticLayer.objects.filter(layer_type="Vector")
|
||||
context["static_layers"] = static_layers
|
||||
return render(request, "layers_list.html", context)
|
||||
except Exception:
|
||||
|
||||
28
apps/management/forms/gto_icon.py
Normal file
@ -0,0 +1,28 @@
|
||||
from django import forms
|
||||
|
||||
from apps.gto.models.model_type_icons import ModelTypeIcons
|
||||
from apps.management.forms.icon import validate_image
|
||||
|
||||
|
||||
class ModelTypeIconsForm(forms.ModelForm):
|
||||
icon = forms.ImageField(
|
||||
required=True,
|
||||
validators=[validate_image],
|
||||
widget=forms.FileInput(
|
||||
attrs={"class": "custom-file-input", "accept": "image/*",
|
||||
"lang": "ru"}
|
||||
),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = ModelTypeIcons
|
||||
fields = ["model", "icon"]
|
||||
widgets = {
|
||||
"model": forms.TextInput(attrs={
|
||||
"autocomplete": "off",
|
||||
"autofocus": True,
|
||||
"class": "form-control",
|
||||
"placeholder": "Введите наименование"
|
||||
}
|
||||
),
|
||||
}
|
||||
36
apps/management/forms/icon.py
Normal file
@ -0,0 +1,36 @@
|
||||
from django import forms
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
from apps.main.models.model_icons import Icons
|
||||
|
||||
|
||||
def validate_image(fieldfile_obj):
|
||||
filesize = fieldfile_obj.size
|
||||
megabyte_limit = 5.0
|
||||
if filesize > megabyte_limit*1024*1024:
|
||||
raise ValidationError("Максимальный размер файла %sMB" % str(megabyte_limit))
|
||||
|
||||
|
||||
class IconForm(forms.ModelForm):
|
||||
image = forms.FileField(
|
||||
required=True,
|
||||
validators=[validate_image],
|
||||
widget=forms.FileInput(
|
||||
attrs={"class": "custom-file-input", "accept": "image/*",
|
||||
"lang": "ru"}
|
||||
),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = Icons
|
||||
fields = ("name", "image")
|
||||
|
||||
labels = {
|
||||
"name": "Наименование",
|
||||
"image": "Изображение",
|
||||
}
|
||||
|
||||
|
||||
widgets = {
|
||||
"name": forms.TextInput(attrs={"class": "form-control", "placeholder": "Введите наименование"}),
|
||||
}
|
||||
175
apps/management/forms/orthomosaic.py
Normal file
@ -0,0 +1,175 @@
|
||||
import os
|
||||
import tempfile
|
||||
from typing import Any
|
||||
|
||||
from django import forms
|
||||
from django.core.exceptions import ValidationError
|
||||
from apps.main.models.model_static_layer import StaticLayer
|
||||
|
||||
from osgeo import gdal, osr
|
||||
|
||||
osr.UseExceptions()
|
||||
|
||||
def check_tif_georeferenced(tif_uploaded_file):
|
||||
"""Проверяет, есть ли в TIF-файле геопривязка, сохраняя его во временный файл."""
|
||||
try:
|
||||
osr.UseExceptions()
|
||||
with tempfile.NamedTemporaryFile(suffix=".tif", delete=False) as tmp_file:
|
||||
for chunk in tif_uploaded_file.chunks():
|
||||
tmp_file.write(chunk)
|
||||
tmp_file_path = tmp_file.name
|
||||
|
||||
dataset = gdal.Open(tmp_file_path)
|
||||
if not dataset:
|
||||
raise ValidationError("Не удалось прочитать TIF-файл.")
|
||||
|
||||
# Проверяем геотрансформацию (если (0,1,0,0,0,1) — файл не геопривязан)
|
||||
transform = dataset.GetGeoTransform()
|
||||
if transform == (0.0, 1.0, 0.0, 0.0, 0.0, 1.0):
|
||||
raise ValidationError(
|
||||
"TIF не содержит геопривязки (все координаты нулевые)."
|
||||
)
|
||||
|
||||
crs = dataset.GetSpatialRef()
|
||||
if not crs:
|
||||
raise ValidationError(
|
||||
"TIF не содержит информации о системе координат (CRS)."
|
||||
)
|
||||
|
||||
dataset = None
|
||||
os.unlink(tmp_file_path)
|
||||
|
||||
except Exception as e:
|
||||
if os.path.exists(tmp_file_path):
|
||||
os.unlink(tmp_file_path)
|
||||
raise ValidationError(f"Ошибка проверки геопривязки: {str(e)}")
|
||||
|
||||
|
||||
def validate_tif_extension(value: Any) -> None:
|
||||
import os
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
ext = os.path.splitext(value.name)[1] # [0] returns path+filename
|
||||
valid_extensions = [".tif"]
|
||||
if not ext.lower() in valid_extensions:
|
||||
raise ValidationError("Данный формат изображения не поддерживается.")
|
||||
|
||||
|
||||
def validate_png_extension(value: Any) -> None:
|
||||
import os
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
ext = os.path.splitext(value.name)[1] # [0] returns path+filename
|
||||
valid_extensions = [".png", ".jpg", ".jpeg"]
|
||||
if not ext.lower() in valid_extensions:
|
||||
raise ValidationError("Данный формат изображения не поддерживается.")
|
||||
|
||||
|
||||
def validate_png_ext_extension(value: Any) -> None:
|
||||
import os
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
ext = os.path.splitext(value.name)[1] # [0] returns path+filename
|
||||
valid_extensions = [".jgw", ".pngw"]
|
||||
if not ext.lower() in valid_extensions:
|
||||
raise ValidationError("Данный формат файла не поддерживается.")
|
||||
|
||||
|
||||
class OrthomosaicForm(forms.ModelForm):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields["name"].widget.attrs["placeholder"] = "Введите наименование"
|
||||
|
||||
if self.instance and self.instance.pk:
|
||||
self.fields.pop("tif_image")
|
||||
self.fields.pop("png_image")
|
||||
self.fields.pop("png_ext_file")
|
||||
else:
|
||||
# self.fields["tif_image"].required = True
|
||||
pass
|
||||
|
||||
tif_image = forms.FileField(
|
||||
required=False,
|
||||
validators=[validate_tif_extension],
|
||||
widget=forms.FileInput(
|
||||
attrs={"class": "custom-file-input", "accept": "image/tiff", "lang": "ru"}
|
||||
),
|
||||
)
|
||||
|
||||
png_image = forms.FileField(
|
||||
required=False,
|
||||
validators=[validate_png_extension],
|
||||
widget=forms.FileInput(
|
||||
attrs={
|
||||
"class": "custom-file-input",
|
||||
"accept": "image/png, image/jpeg",
|
||||
"lang": "ru",
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
png_ext_file = forms.FileField(
|
||||
required=False,
|
||||
validators=[validate_png_ext_extension],
|
||||
widget=forms.FileInput(
|
||||
attrs={
|
||||
"class": "custom-file-input",
|
||||
"accept": ".pngw,.jgw",
|
||||
"lang": "ru",
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = StaticLayer
|
||||
fields = ("name", "is_visible", "tif_image", "png_image", "png_ext_file", "order")
|
||||
labels = {
|
||||
"name": "Наименование",
|
||||
"is_visible": "Видимый",
|
||||
"order": "Порядок наложения",
|
||||
}
|
||||
|
||||
widgets = {
|
||||
"name": forms.TextInput(attrs={"class": "form-control"}),
|
||||
"order": forms.NumberInput(attrs={"class": "form-control", "min": "0", "max": "100"}),
|
||||
}
|
||||
|
||||
def clean(self):
|
||||
data = super().clean()
|
||||
|
||||
tif_uploaded = bool(data.get("tif_image"))
|
||||
|
||||
png_file_uploaded = bool(data.get("png_image"))
|
||||
png_ext_file_uploaded = bool(data.get("png_ext_file"))
|
||||
|
||||
if tif_uploaded and (png_file_uploaded or png_ext_file_uploaded):
|
||||
raise ValidationError(
|
||||
"Загрузите только один ортофотоплан. (только TIF, либо только PNG + PNGW"
|
||||
)
|
||||
|
||||
if png_file_uploaded and not png_ext_file_uploaded:
|
||||
self.add_error(
|
||||
"png_ext_file", ValidationError("Загрузите World файл для изображения")
|
||||
)
|
||||
|
||||
elif png_ext_file_uploaded and not png_file_uploaded:
|
||||
self.add_error(
|
||||
"png_image", ValidationError("Загрузите основное изображение")
|
||||
)
|
||||
|
||||
if tif_uploaded:
|
||||
try:
|
||||
check_tif_georeferenced(data.get("tif_image"))
|
||||
except ValidationError as e:
|
||||
self.add_error("tif_image", e)
|
||||
|
||||
# if png_file_uploaded and png_ext_file_uploaded:
|
||||
# png = data.get("png_image")
|
||||
# png_ext = data.get("png_ext_file")
|
||||
# if png.name != png_ext.name[:len(png.name)]:
|
||||
# self.add_error("png_image", "Имя изображения и world файла должны совпадать")
|
||||
# self.add_error("png_ext_file", "Имя изображения и world файла должны совпадать")
|
||||
return data
|
||||
@ -1,144 +0,0 @@
|
||||
{% extends "default.html" %}
|
||||
{% load static %}
|
||||
{% load mysettings %}
|
||||
|
||||
|
||||
{% block header_link %}
|
||||
<!-- Select2 -->
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/select2/css/select2.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<!-- iCheck for checkboxes and radio inputs -->
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/icheck-bootstrap/icheck-bootstrap.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<style>
|
||||
.file-upload-label {
|
||||
cursor: pointer;
|
||||
border: 1px solid #ced4da;
|
||||
padding: .375rem .75rem;
|
||||
border-radius: .25rem;
|
||||
font-weight: normal !important;
|
||||
}
|
||||
</style>
|
||||
{% endblock header_link %}
|
||||
{% block content %}
|
||||
<section class="content-header">
|
||||
<div class="container-fluid">
|
||||
<div class="row mb-2">
|
||||
<div class="col-sm-6">
|
||||
<h4>Добавление ортофотоплана</h4>
|
||||
</div>
|
||||
<div class="col-sm-6">
|
||||
<ol class="breadcrumb float-sm-right">
|
||||
<li class="breadcrumb-item"><a href="/management/">Главная</a></li>
|
||||
<li class="breadcrumb-item"><a href="/management/">Параметры системы </a></li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</div><!-- /.container-fluid -->
|
||||
</section>
|
||||
|
||||
<section class="content">
|
||||
<form autocomplete="off" method="post" enctype="multipart/form-data" class="form-horizontal">
|
||||
{% csrf_token %}
|
||||
<div class="container-fluid">
|
||||
<div class="row">
|
||||
<!-- /.col -->
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
{% if error %}
|
||||
<div class="alert alert-danger alert-dismissible">
|
||||
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×
|
||||
</button>
|
||||
<h4><i class="icon fa fa-ban"></i> Внимание !</h4>
|
||||
{% for com in error_comment %}
|
||||
<p margin:0;margin-left:10px; ">{{ com }}</p>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="form-group row">
|
||||
<label for="min_lon" class="col-sm-2 col-form-label">Минимальная широта: </label>
|
||||
<div class="col-sm-4">
|
||||
<input autocomplete="off" type="text" name="min_lon" class="form-control"
|
||||
autofocus="" required id="min_lon" value="{{ orth_minLon }}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group row">
|
||||
<label for="min_lat" class="col-sm-2 col-form-label">Минимальная долгота: </label>
|
||||
<div class="col-sm-4">
|
||||
<input autocomplete="off" type="text" name="min_lat" class="form-control"
|
||||
autofocus="" required id="min_lat" value="{{ orth_minLat }}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group row">
|
||||
<label for="max_lon" class="col-sm-2 col-form-label">Максимальная широта: </label>
|
||||
<div class="col-sm-4">
|
||||
<input autocomplete="off" type="text" name="max_lon" class="form-control"
|
||||
autofocus="" required id="max_lon" value="{{ orth_maxLon }}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group row">
|
||||
<label for="max_lat" class="col-sm-2 col-form-label">Максимальная долгота: </label>
|
||||
<div class="col-sm-4">
|
||||
<input autocomplete="off" type="text" name="max_lat" class="form-control"
|
||||
autofocus="" required id="max_lat" value="{{ orth_maxLat }}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group row">
|
||||
<label for="id_last_name" class="col-sm-2 col-form-label">Архив: </label>
|
||||
<div class="col-sm-4">
|
||||
<label for="icon"
|
||||
class="col-sm-1 col-form-label">{{ gto_icon.model }}</label>
|
||||
<div style="display: flex; flex-direction: column">
|
||||
<label for="archive" class="file-upload-label">Выберите
|
||||
архив</label>
|
||||
<input type="file" name="archive"
|
||||
class="form-control show-name" autofocus=""
|
||||
id="archive" style="visibility:hidden; display: none"
|
||||
accept=".zip" required>
|
||||
<div id="file-name" class="file-name"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p>
|
||||
<i class="fas fa-info-circle" style="color: var(--primary);"></i>
|
||||
Необходимо загрузить архив в соответствии с TMS
|
||||
</p>
|
||||
</div><!-- /.card-body -->
|
||||
<div class="card-footer">
|
||||
<button id="btnok" type="submit" class="btn bg-gradient-primary">Сохранить</button>
|
||||
<a href="/management/" type="button" class="btn btn-default float-right">Отмена</a>
|
||||
</div>
|
||||
</div>
|
||||
<!-- /.nav-tabs-custom -->
|
||||
</div>
|
||||
<!-- /.col -->
|
||||
</div>
|
||||
<!-- /.row -->
|
||||
</div><!-- /.container-fluid -->
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
{% block script_footer %}
|
||||
<script>
|
||||
const inputArr = document.querySelectorAll('.show-name')
|
||||
for (let arr of inputArr) {
|
||||
arr.addEventListener('change', function (event) {
|
||||
const fileNameDisplay = document.getElementById('file-name');
|
||||
const file = event.target.files[0];
|
||||
|
||||
if (file) {
|
||||
fileNameDisplay.style.display = 'block';
|
||||
fileNameDisplay.innerHTML = `Сейчас выбран: <a href="#" download="${file.name}">${file.name}</a>`;
|
||||
} else {
|
||||
fileNameDisplay.style.display = 'none';
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
{% endblock script_footer %}
|
||||
|
||||
@ -48,39 +48,49 @@
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
{% if error %}
|
||||
{% if form.errors %}
|
||||
<div class="alert alert-danger alert-dismissible">
|
||||
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×
|
||||
</button>
|
||||
<h4><i class="icon fa fa-ban"></i> Внимание !</h4>
|
||||
{% for com in error_comment %}
|
||||
<p margin:0;margin-left:10px; ">{{ com }}</p>
|
||||
{% for field, errors in form.errors.items %}
|
||||
{% for error in errors %}
|
||||
<p style="margin:0;margin-left:10px;">{{ error }}</p>
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="form-group row">
|
||||
<label for="id_model" class="col-sm-2 col-form-label">Вид
|
||||
оборудования: </label>
|
||||
<label for="{{ form.model.id_for_label }}" class="col-sm-2 col-form-label">Вид
|
||||
оборудования:</label>
|
||||
<div class="col-sm-4">
|
||||
<input autocomplete="off" type="text" name="model" class="form-control"
|
||||
autofocus="" required="" id="id_model">
|
||||
{{ form.model }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group row">
|
||||
<label for="id_last_name" class="col-sm-2 col-form-label">Изображение: </label>
|
||||
<div class="col-sm-4">
|
||||
<label for="icon"
|
||||
class="col-sm-1 col-form-label">{{ gto_icon.model }}</label>
|
||||
<div>
|
||||
<label for="icon" class="file-upload-label">Выберите
|
||||
изображение</label><br>
|
||||
<input type="file" name="icon"
|
||||
class="form-control autosubmit" autofocus=""
|
||||
id="icon" style="visibility:hidden;"
|
||||
accept="image/png">
|
||||
<label for="{{ form.icon.id_for_label }}" class="col-sm-2 col-form-label">
|
||||
Изображение
|
||||
<span class="text-danger">*</span>
|
||||
</label>
|
||||
<div class="col-sm-8">
|
||||
<div class="custom-file">
|
||||
{{ form.icon }}
|
||||
<span class="file-name"></span>
|
||||
<label class="custom-file-label"
|
||||
for="{{ form.icon.id_form_label }}">
|
||||
Выберите изображение
|
||||
</label>
|
||||
{% if form.icon.errors %}
|
||||
<div class="invalid-feedback d-block">
|
||||
{% for error in form.icon.errors %}
|
||||
<p>{{ error }}</p>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div><!-- /.card-body -->
|
||||
<div class="card-footer">
|
||||
|
||||
276
apps/management/templates/icons/form_icon.html
Normal file
@ -0,0 +1,276 @@
|
||||
{% extends "default.html" %}
|
||||
{% load static %}
|
||||
{% load mysettings %}
|
||||
|
||||
|
||||
{% block header_link %}
|
||||
<!-- Select2 -->
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/select2/css/select2.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<!-- iCheck for checkboxes and radio inputs -->
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/icheck-bootstrap/icheck-bootstrap.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<style>
|
||||
.file-upload-label {
|
||||
cursor: pointer;
|
||||
border: 1px solid #ced4da;
|
||||
padding: .375rem .75rem;
|
||||
border-radius: .25rem;
|
||||
font-weight: normal !important;
|
||||
}
|
||||
|
||||
.custom-file {
|
||||
margin-bottom: 1.5em;
|
||||
}
|
||||
|
||||
.file-name {
|
||||
margin-left: .5em;
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
</style>
|
||||
{% endblock header_link %}
|
||||
{% block content %}
|
||||
<section class="content-header">
|
||||
<div class="container-fluid">
|
||||
<div class="row mb-2">
|
||||
<div class="col-sm-6">
|
||||
<h4>{% if form.instance.pk %}Редактирование{% else %}Добавление{% endif %} изображения</h4>
|
||||
</div>
|
||||
<div class="col-sm-6">
|
||||
<ol class="breadcrumb float-sm-right">
|
||||
<li class="breadcrumb-item"><a href="{% url 'mainindex' %}">Главная</a></li>
|
||||
<li class="breadcrumb-item"><a href="{% url 'management:main_index' %}">Параметры системы </a>
|
||||
</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</div><!-- /.container-fluid -->
|
||||
</section>
|
||||
|
||||
<section class="content">
|
||||
<form autocomplete="off" method="post" enctype="multipart/form-data" class="form-horizontal" id="form">
|
||||
{% csrf_token %}
|
||||
<div class="container-fluid">
|
||||
<div class="row">
|
||||
<!-- /.col -->
|
||||
<div class="col-12">
|
||||
<div class="card card-outline card-primary">
|
||||
<div class="card-body">
|
||||
<div class="form-group row">
|
||||
<label for="{{ form.name.id_for_label }}" class="col-sm-2 col-form-label">
|
||||
Наименование
|
||||
<span class="text-danger">*</span>
|
||||
</label>
|
||||
<div class="col-sm-8">
|
||||
{{ form.name }}
|
||||
{% if form.name.errors %}
|
||||
<div class="invalid-feedback d-block">
|
||||
{% for error in form.name.errors %}
|
||||
<p>{{ error }}</p>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% if form.instance.pk %}
|
||||
<div class="form-group row">
|
||||
<label class="col-sm-2 col-form-label">
|
||||
Предпросмотр
|
||||
</label>
|
||||
<div class="col-sm-8">
|
||||
<img src="{{ form.instance.image.url }}"
|
||||
style="width: 200px; height: 200px;" alt="">
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="form-group row">
|
||||
<label for="{{ form.image.id_for_label }}" class="col-sm-2 col-form-label">
|
||||
Изображение
|
||||
<span class="text-danger">*</span>
|
||||
</label>
|
||||
<div class="col-sm-8">
|
||||
<div class="custom-file">
|
||||
{{ form.image }}
|
||||
<span class="file-name"></span>
|
||||
<label class="custom-file-label"
|
||||
for="{{ form.image.id_form_label }}">
|
||||
Выберите изображение
|
||||
</label>
|
||||
{% if form.image.errors %}
|
||||
<div class="invalid-feedback d-block">
|
||||
{% for error in form.image.errors %}
|
||||
<p>{{ error }}</p>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="card-footer">
|
||||
<button id="saveButton" type="submit" class="btn bg-gradient-primary">Сохранить</button>
|
||||
<a href="/management/" type="button" class="btn btn-default float-right">Отмена</a>
|
||||
</div>
|
||||
<!-- /.card -->
|
||||
</div>
|
||||
<!-- /.nav-tabs-custom -->
|
||||
</div>
|
||||
<!-- /.col -->
|
||||
</div>
|
||||
<!-- /.row -->
|
||||
</div><!-- /.container-fluid -->
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
{% block script_footer %}
|
||||
|
||||
<script src="{% static 'js/ol/lib/OpenLayers.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/ol-ext/ol-ext.min.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/layersStyles.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/map/map-core.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/map/map-layer-switcher.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/map/map-marker-manager.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/map/map-created-layer-manager.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/map/map-time-slider.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/map/map-coefficients-manager.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
|
||||
<script>
|
||||
document.getElementById("saveButton").addEventListener("click", (event) => {
|
||||
$("#saveButtonIcon").hide()
|
||||
event.target.insertAdjacentHTML('afterbegin', `
|
||||
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
|
||||
`);
|
||||
event.target.disabled = true
|
||||
document.getElementById("form").submit()
|
||||
})
|
||||
|
||||
</script>
|
||||
<script>
|
||||
const inputArr = document.querySelectorAll('.custom-file')
|
||||
for (let div of inputArr) {
|
||||
div.querySelector("input").addEventListener('change', function (event) {
|
||||
const fileNameDisplay = div.querySelector("span.file-name");
|
||||
const file = event.target.files[0];
|
||||
|
||||
if (file) {
|
||||
fileNameDisplay.style.display = 'block';
|
||||
fileNameDisplay.innerHTML = `Сейчас выбран: <a href="#" download="${file.name}">${file.name}</a>`;
|
||||
} else {
|
||||
fileNameDisplay.style.display = 'none';
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
<script>
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
// Находим все вкладки и их контент
|
||||
const tabs = document.querySelectorAll('.nav-link');
|
||||
const tabContent = document.querySelectorAll('.tab-pane');
|
||||
|
||||
// Функция для активации вкладки
|
||||
function activateTab(tabId) {
|
||||
tabs.forEach(tab => {
|
||||
tab.classList.remove('active');
|
||||
tab.setAttribute('aria-selected', 'false');
|
||||
});
|
||||
|
||||
tabContent.forEach(content => {
|
||||
content.classList.remove('active', 'show');
|
||||
});
|
||||
|
||||
const selectedTab = document.querySelector(`[href="#${tabId}"]`);
|
||||
if (selectedTab) {
|
||||
selectedTab.classList.add('active');
|
||||
selectedTab.setAttribute('aria-selected', 'true');
|
||||
}
|
||||
|
||||
const selectedContent = document.getElementById(tabId);
|
||||
if (selectedContent) {
|
||||
selectedContent.classList.add('active', 'show');
|
||||
}
|
||||
}
|
||||
|
||||
// Проверяем, есть ли сохраненная вкладка в localStorage
|
||||
const savedTab = localStorage.getItem('activeTab');
|
||||
if (savedTab) {
|
||||
activateTab(savedTab);
|
||||
} else {
|
||||
// Если нет сохраненной вкладки, активируем первую по умолчанию
|
||||
activateTab('tiff');
|
||||
}
|
||||
|
||||
// Добавляем обработчики событий для вкладок
|
||||
tabs.forEach(tab => {
|
||||
tab.addEventListener('click', function (event) {
|
||||
event.preventDefault();
|
||||
const tabId = this.getAttribute('href').substring(1); // Убираем символ '#'
|
||||
activateTab(tabId);
|
||||
|
||||
// Сохраняем выбранную вкладку в localStorage
|
||||
localStorage.setItem('activeTab', tabId);
|
||||
});
|
||||
});
|
||||
});
|
||||
</script>
|
||||
<script>
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
const extent = ol.proj.transformExtent(
|
||||
[
|
||||
parseFloat('{{ form.instance.min_lon|safe }}'),
|
||||
parseFloat('{{ form.instance.min_lat|safe }}'),
|
||||
parseFloat('{{ form.instance.max_lon|safe }}'),
|
||||
parseFloat('{{ form.instance.max_lat|safe }}')
|
||||
],
|
||||
'EPSG:4326', // Исходная проекция
|
||||
'EPSG:3857' // Целевая проекция
|
||||
);
|
||||
const mapCore = new MapCore('map', {
|
||||
center: ['{{longitude}}', '{{latitude}}'],
|
||||
zoom: 12
|
||||
});
|
||||
await mapCore.initialize();
|
||||
const scanLayer = new ol.layer.Tile({
|
||||
source: new ol.source.XYZ({
|
||||
url: `{{ form.instance.url }}`,
|
||||
}),
|
||||
extent: extent
|
||||
});
|
||||
scanLayer.set('title', 'Ортофотоплан')
|
||||
scanLayer.set('name', 'orto')
|
||||
mapCore.addLayer(scanLayer)
|
||||
|
||||
|
||||
mapCore.map.getView().fit(extent, {
|
||||
padding: [20, 20, 20, 20],
|
||||
duration: 1000,
|
||||
maxZoom: 15
|
||||
});
|
||||
|
||||
const extentPolygon = ol.geom.Polygon.fromExtent(extent);
|
||||
|
||||
const vectorLayer = new ol.layer.Vector({
|
||||
source: new ol.source.Vector({
|
||||
features: [
|
||||
new ol.Feature({
|
||||
geometry: extentPolygon,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
style: new ol.style.Style({
|
||||
stroke: new ol.style.Stroke({
|
||||
color: 'red',
|
||||
width: 2,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
mapCore.addLayer(vectorLayer)
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
{% endblock script_footer %}
|
||||
|
||||
87
apps/management/templates/icons/manage_icon.html
Normal file
@ -0,0 +1,87 @@
|
||||
{% extends "default.html" %}
|
||||
{% load static %}
|
||||
{% load mysettings %}
|
||||
|
||||
{% block header_link %}
|
||||
<!-- Select2 -->
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/select2/css/select2.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<!-- iCheck for checkboxes and radio inputs -->
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/icheck-bootstrap/icheck-bootstrap.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
{% endblock header_link %}
|
||||
|
||||
|
||||
{% block content %}
|
||||
<section class="content-header">
|
||||
<div class="container-fluid">
|
||||
<div class="row mb-2">
|
||||
<div class="col-sm-6">
|
||||
<h4>{% if form.instance.pk %}Редактирование{% else %}Добавление{% endif %} изображениями</h4>
|
||||
</div>
|
||||
<div class="col-sm-6">
|
||||
<ol class="breadcrumb float-sm-right">
|
||||
<li class="breadcrumb-item"><a href="{% url 'mainindex' %}">Главная</a></li>
|
||||
<li class="breadcrumb-item"><a href="{% url 'management:main_index' %}">Параметры системы </a>
|
||||
</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</div><!-- /.container-fluid -->
|
||||
</section>
|
||||
|
||||
<section class="content">
|
||||
<form autocomplete="off" method="post" enctype="multipart/form-data" class="form-horizontal">
|
||||
{% csrf_token %}
|
||||
<div class="container-fluid">
|
||||
<div class="row">
|
||||
<!-- /.col -->
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<a href="{% url 'management:add_icon' %}" class="btn btn-primary">Добавить</a>
|
||||
</div>
|
||||
<div class="card-body table-responsive p-0">
|
||||
<table class="table table-bordered table-hover table-head-fixed text-nowrap">
|
||||
<thead>
|
||||
<tr role="row">
|
||||
<th class="col-1"></th>
|
||||
<th>Наименование</th>
|
||||
<th>Предпросмотр</th>
|
||||
<th class="col-1"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
|
||||
{% for icon in catalog %}
|
||||
<tr>
|
||||
<td>
|
||||
{{ icon.id }}
|
||||
</td>
|
||||
<td>
|
||||
<a href="{% url 'management:edit_icon' icon.id %}">{{ icon.name }}</a>
|
||||
</td>
|
||||
<td>
|
||||
<img src="{{ icon.image.url }}" alt=""
|
||||
style="width: 100px; height: 100px;">
|
||||
</td>
|
||||
<td><a href="{% url 'management:remove_icon' icon.id %}"
|
||||
class="btn btn-danger btn-block btn-sm"><i class="fa fa-trash"></i>
|
||||
Удалить</a></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div> <!-- /.card-body -->
|
||||
</div>
|
||||
<!-- /.nav-tabs-custom -->
|
||||
</div>
|
||||
<!-- /.col -->
|
||||
</div>
|
||||
<!-- /.row -->
|
||||
</div><!-- /.container-fluid -->
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
87
apps/management/templates/icons/remove_icon.html
Normal file
@ -0,0 +1,87 @@
|
||||
{% extends "default.html" %}
|
||||
{% load static %}
|
||||
{% load mysettings %}
|
||||
|
||||
|
||||
{% block header_link %}
|
||||
<!-- Select2 -->
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/select2/css/select2.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<!-- iCheck for checkboxes and radio inputs -->
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/icheck-bootstrap/icheck-bootstrap.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<style>
|
||||
.file-upload-label {
|
||||
cursor: pointer;
|
||||
border: 1px solid #ced4da;
|
||||
padding: .375rem .75rem;
|
||||
border-radius: .25rem;
|
||||
font-weight: normal !important;
|
||||
}
|
||||
</style>
|
||||
{% endblock header_link %}
|
||||
{% block content %}
|
||||
<section class="content-header">
|
||||
<div class="container-fluid">
|
||||
<div class="row mb-2">
|
||||
<div class="col-sm-6">
|
||||
<h4>Удаление ортофотоплана</h4>
|
||||
</div>
|
||||
<div class="col-sm-6">
|
||||
<ol class="breadcrumb float-sm-right">
|
||||
<li class="breadcrumb-item"><a href="/management/">Главная</a></li>
|
||||
<li class="breadcrumb-item"><a href="/management/">Параметры системы</a></li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</div><!-- /.container-fluid -->
|
||||
</section>
|
||||
|
||||
<section class="content">
|
||||
<form autocomplete="off" method="post" class="form-horizontal">
|
||||
{% csrf_token %}
|
||||
<div class="container-fluid">
|
||||
<div class="row">
|
||||
<!-- /.col -->
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-header">Удаление ортофотоплана</div>
|
||||
<div class="card-body">
|
||||
<p>Вы уверены, что хотите удалить изображение: {{ object.name }}?</p>
|
||||
</div><!-- /.card-body -->
|
||||
<div class="card-footer">
|
||||
<button id="btnok" type="submit" class="btn bg-gradient-danger">Удалить</button>
|
||||
<a href="/management/" type="button" class="btn btn-default float-right">Отмена</a>
|
||||
</div>
|
||||
</div>
|
||||
<!-- /.nav-tabs-custom -->
|
||||
</div>
|
||||
<!-- /.col -->
|
||||
</div>
|
||||
<!-- /.row -->
|
||||
</div><!-- /.container-fluid -->
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
{% block script_footer %}
|
||||
<script>
|
||||
const inputArr = document.querySelectorAll('.show-name')
|
||||
for (let arr of inputArr) {
|
||||
arr.addEventListener('change', function (event) {
|
||||
const fileNameDisplay = document.getElementById('file-name');
|
||||
const file = event.target.files[0];
|
||||
|
||||
if (file) {
|
||||
fileNameDisplay.style.display = 'block';
|
||||
fileNameDisplay.innerHTML = `Сейчас выбран: <a href="#" download="${file.name}">${file.name}</a>`;
|
||||
} else {
|
||||
fileNameDisplay.style.display = 'none';
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
{% endblock script_footer %}
|
||||
|
||||
340
apps/management/templates/orthomosaic/form_orthomosaic.html
Normal file
@ -0,0 +1,340 @@
|
||||
{% extends "default.html" %}
|
||||
{% load static %}
|
||||
{% load mysettings %}
|
||||
|
||||
|
||||
{% block header_link %}
|
||||
<!-- Select2 -->
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/select2/css/select2.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<!-- iCheck for checkboxes and radio inputs -->
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/icheck-bootstrap/icheck-bootstrap.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<style>
|
||||
.file-upload-label {
|
||||
cursor: pointer;
|
||||
border: 1px solid #ced4da;
|
||||
padding: .375rem .75rem;
|
||||
border-radius: .25rem;
|
||||
font-weight: normal !important;
|
||||
}
|
||||
|
||||
.custom-file {
|
||||
margin-bottom: 1.5em;
|
||||
}
|
||||
|
||||
.file-name {
|
||||
margin-left: .5em;
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
</style>
|
||||
{% endblock header_link %}
|
||||
{% block content %}
|
||||
<section class="content-header">
|
||||
<div class="container-fluid">
|
||||
<div class="row mb-2">
|
||||
<div class="col-sm-6">
|
||||
<h4>{% if form.instance.pk %}Редактирование{% else %}Добавление{% endif %} ортофотоплана</h4>
|
||||
</div>
|
||||
<div class="col-sm-6">
|
||||
<ol class="breadcrumb float-sm-right">
|
||||
<li class="breadcrumb-item"><a href="{% url 'mainindex' %}">Главная</a></li>
|
||||
<li class="breadcrumb-item"><a href="{% url 'management:main_index' %}">Параметры системы </a></li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</div><!-- /.container-fluid -->
|
||||
</section>
|
||||
|
||||
<section class="content">
|
||||
<form autocomplete="off" method="post" enctype="multipart/form-data" class="form-horizontal" id="form">
|
||||
{% csrf_token %}
|
||||
<div class="container-fluid">
|
||||
<div class="row">
|
||||
<!-- /.col -->
|
||||
<div class="col-12">
|
||||
<div class="card card-outline card-primary">
|
||||
<div class="card-body">
|
||||
<div class="form-group row">
|
||||
<label for="{{ form.name.id_for_label }}" class="col-sm-2 col-form-label">
|
||||
Наименование <span class="text-danger">*</span>
|
||||
</label>
|
||||
<div class="col-sm-8">
|
||||
{{ form.name }}
|
||||
{% if form.name.errors %}
|
||||
<div class="invalid-feedback d-block">
|
||||
{% for error in form.name.errors %}
|
||||
<p>{{ error }}</p>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% if not form.instance.pk %}
|
||||
<div class="row">
|
||||
<div class="col-sm-2 p-0 pt-3 pb-3">
|
||||
<div class="nav flex-column nav-tabs h-100" id="vert-tabs-tab"
|
||||
role="tablist"
|
||||
aria-orientation="vertical">
|
||||
<a class="nav-link active" id="tiff-tab" data-toggle="pill"
|
||||
href="#tiff" role="tab" aria-controls="tiff"
|
||||
aria-selected="true">TIFF</a>
|
||||
<a class="nav-link" id="png-tab" data-toggle="pill"
|
||||
href="#png" role="tab" aria-controls="png"
|
||||
aria-selected="false">PNG/JPEG</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-sm-8 pt-3 pb-3">
|
||||
<div class="tab-content" id="vert-tabs-tabContent">
|
||||
<div class="tab-pane fade active show" id="tiff" role="tabpanel"
|
||||
aria-labelledby="tiff-tab">
|
||||
<div class="custom-file">
|
||||
{{ form.tif_image }}
|
||||
<span class="file-name"></span>
|
||||
<label class="custom-file-label"
|
||||
for="{{ form.tif_image.id_form_label }}">
|
||||
Выберите TIFF файл
|
||||
</label>
|
||||
{% if form.tif_image.errors %}
|
||||
<div class="invalid-feedback d-block">
|
||||
{% for error in form.tif_image.errors %}
|
||||
<p>{{ error }}</p>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="tab-pane fade " id="png"
|
||||
role="tabpanel" aria-labelledby="png-tab">
|
||||
<div class="custom-file">
|
||||
{{ form.png_image }}
|
||||
<span class="file-name"></span>
|
||||
<label class="custom-file-label"
|
||||
for="{{ form.png_image.id_form_label }}">
|
||||
Выберите PNG/JPEG файл
|
||||
</label>
|
||||
{% if form.png_image.errors %}
|
||||
<div class="invalid-feedback d-block">
|
||||
{% for error in form.png_image.errors %}
|
||||
<p>{{ error }}</p>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="custom-file">
|
||||
{{ form.png_ext_file }}
|
||||
<span class="file-name"></span>
|
||||
<label class="custom-file-label"
|
||||
for="{{ form.png_ext_file.id_form_label }}">
|
||||
Выберите PNGW/JGW файл
|
||||
</label>
|
||||
{% if form.png_ext_file.errors %}
|
||||
<div class="invalid-feedback d-block">
|
||||
{% for error in form.png_ext_file.errors %}
|
||||
<p>{{ error }}</p>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="form-group row">
|
||||
<label
|
||||
class="col-sm-2 col-form-label">
|
||||
Предпросмотр
|
||||
</label>
|
||||
<div class="col-sm-8">
|
||||
<div id="map" style="height: 500px;"></div>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="form-group row">
|
||||
<label for="{{ form.order.id_for_label }}"
|
||||
class="col-sm-2 col-form-label">
|
||||
Порядок наложения
|
||||
</label>
|
||||
<div class="col-sm-8">
|
||||
{{ form.order }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group row">
|
||||
<label for="{{ form.is_visible.id_for_label }}"
|
||||
class="col-sm-2 col-form-label">
|
||||
Активен
|
||||
</label>
|
||||
<div class="col-sm-8">
|
||||
{{ form.is_visible }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
<div class="card-footer">
|
||||
<button id="saveButton" type="submit" class="btn bg-gradient-primary">Сохранить</button>
|
||||
<a href="/management/" type="button" class="btn btn-default float-right">Отмена</a>
|
||||
</div>
|
||||
<!-- /.card -->
|
||||
</div>
|
||||
<!-- /.nav-tabs-custom -->
|
||||
</div>
|
||||
<!-- /.col -->
|
||||
</div>
|
||||
<!-- /.row -->
|
||||
</div><!-- /.container-fluid -->
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
{% block script_footer %}
|
||||
|
||||
<script src="{% static 'js/ol/lib/OpenLayers.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/ol-ext/ol-ext.min.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/layersStyles.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/map/map-core.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/map/map-layer-switcher.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/map/map-marker-manager.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/map/map-created-layer-manager.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/map/map-time-slider.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static 'js/ol/map/map-coefficients-manager.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
|
||||
<script>
|
||||
document.getElementById("saveButton").addEventListener("click", (event) => {
|
||||
$("#saveButtonIcon").hide()
|
||||
event.target.insertAdjacentHTML('afterbegin', `
|
||||
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
|
||||
`);
|
||||
event.target.disabled = true
|
||||
document.getElementById("form").submit()
|
||||
})
|
||||
|
||||
</script>
|
||||
<script>
|
||||
const inputArr = document.querySelectorAll('.custom-file')
|
||||
for (let div of inputArr) {
|
||||
div.querySelector("input").addEventListener('change', function (event) {
|
||||
const fileNameDisplay = div.querySelector("span.file-name");
|
||||
const file = event.target.files[0];
|
||||
|
||||
if (file) {
|
||||
fileNameDisplay.style.display = 'block';
|
||||
fileNameDisplay.innerHTML = `Сейчас выбран: <a href="#" download="${file.name}">${file.name}</a>`;
|
||||
} else {
|
||||
fileNameDisplay.style.display = 'none';
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
<script>
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
// Находим все вкладки и их контент
|
||||
const tabs = document.querySelectorAll('.nav-link');
|
||||
const tabContent = document.querySelectorAll('.tab-pane');
|
||||
|
||||
// Функция для активации вкладки
|
||||
function activateTab(tabId) {
|
||||
tabs.forEach(tab => {
|
||||
tab.classList.remove('active');
|
||||
tab.setAttribute('aria-selected', 'false');
|
||||
});
|
||||
|
||||
tabContent.forEach(content => {
|
||||
content.classList.remove('active', 'show');
|
||||
});
|
||||
|
||||
const selectedTab = document.querySelector(`[href="#${tabId}"]`);
|
||||
if (selectedTab) {
|
||||
selectedTab.classList.add('active');
|
||||
selectedTab.setAttribute('aria-selected', 'true');
|
||||
}
|
||||
|
||||
const selectedContent = document.getElementById(tabId);
|
||||
if (selectedContent) {
|
||||
selectedContent.classList.add('active', 'show');
|
||||
}
|
||||
}
|
||||
|
||||
// Проверяем, есть ли сохраненная вкладка в localStorage
|
||||
const savedTab = localStorage.getItem('activeTab');
|
||||
if (savedTab) {
|
||||
activateTab(savedTab);
|
||||
} else {
|
||||
// Если нет сохраненной вкладки, активируем первую по умолчанию
|
||||
activateTab('tiff');
|
||||
}
|
||||
|
||||
// Добавляем обработчики событий для вкладок
|
||||
tabs.forEach(tab => {
|
||||
tab.addEventListener('click', function (event) {
|
||||
event.preventDefault();
|
||||
const tabId = this.getAttribute('href').substring(1); // Убираем символ '#'
|
||||
activateTab(tabId);
|
||||
|
||||
// Сохраняем выбранную вкладку в localStorage
|
||||
localStorage.setItem('activeTab', tabId);
|
||||
});
|
||||
});
|
||||
});
|
||||
</script>
|
||||
<script>
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
const extent = ol.proj.transformExtent(
|
||||
[
|
||||
parseFloat('{{ form.instance.min_lon|safe }}'),
|
||||
parseFloat('{{ form.instance.min_lat|safe }}'),
|
||||
parseFloat('{{ form.instance.max_lon|safe }}'),
|
||||
parseFloat('{{ form.instance.max_lat|safe }}')
|
||||
],
|
||||
'EPSG:4326', // Исходная проекция
|
||||
'EPSG:3857' // Целевая проекция
|
||||
);
|
||||
const mapCore = new MapCore('map', {
|
||||
center: ['{{longitude}}', '{{latitude}}'],
|
||||
zoom: 12
|
||||
});
|
||||
await mapCore.initialize();
|
||||
const scanLayer = new ol.layer.Tile({
|
||||
source: new ol.source.XYZ({
|
||||
url: `{{ form.instance.url }}`,
|
||||
}),
|
||||
extent: extent
|
||||
});
|
||||
scanLayer.set('title', 'Ортофотоплан')
|
||||
scanLayer.set('name', 'orto')
|
||||
mapCore.addLayer(scanLayer)
|
||||
|
||||
|
||||
mapCore.map.getView().fit(extent, {
|
||||
padding: [20, 20, 20, 20],
|
||||
duration: 1000,
|
||||
maxZoom: 15
|
||||
});
|
||||
|
||||
const extentPolygon = ol.geom.Polygon.fromExtent(extent);
|
||||
|
||||
const vectorLayer = new ol.layer.Vector({
|
||||
source: new ol.source.Vector({
|
||||
features: [
|
||||
new ol.Feature({
|
||||
geometry: extentPolygon,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
style: new ol.style.Style({
|
||||
stroke: new ol.style.Stroke({
|
||||
color: 'red',
|
||||
width: 2,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
mapCore.addLayer(vectorLayer)
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
{% endblock script_footer %}
|
||||
|
||||
@ -0,0 +1,79 @@
|
||||
{% extends "default.html" %}
|
||||
{% load static %}
|
||||
{% load mysettings %}
|
||||
|
||||
{% block header_link %}
|
||||
<!-- Select2 -->
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/select2/css/select2.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
<!-- iCheck for checkboxes and radio inputs -->
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'lte/plugins/icheck-bootstrap/icheck-bootstrap.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||||
{% endblock header_link %}
|
||||
|
||||
|
||||
{% block content %}
|
||||
<section class="content-header">
|
||||
<div class="container-fluid">
|
||||
<div class="row mb-2">
|
||||
<div class="col-sm-6">
|
||||
<h4>Управление ортофотопланами</h4>
|
||||
</div>
|
||||
<div class="col-sm-6">
|
||||
<ol class="breadcrumb float-sm-right">
|
||||
<li class="breadcrumb-item"><a href="{% url 'mainindex' %}">Главная</a></li>
|
||||
<li class="breadcrumb-item"><a href="{% url 'management:main_index' %}">Параметры системы </a></li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</div><!-- /.container-fluid -->
|
||||
</section>
|
||||
|
||||
<section class="content">
|
||||
<form autocomplete="off" method="post" enctype="multipart/form-data" class="form-horizontal">
|
||||
{% csrf_token %}
|
||||
<div class="container-fluid">
|
||||
<div class="row">
|
||||
<!-- /.col -->
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<a href="{% url 'management:add_orthomosaic' %}" class="btn btn-primary">Добавить</a>
|
||||
</div>
|
||||
<div class="card-body table-responsive p-0">
|
||||
<table class="table table-bordered table-hover table-head-fixed text-nowrap">
|
||||
<thead>
|
||||
<tr role="row">
|
||||
<th class="col-1"></th>
|
||||
<th>Наименование</th>
|
||||
<th class="col-1"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
|
||||
{% for ortho in catalog %}
|
||||
<tr>
|
||||
<td>
|
||||
{{ ortho.id }}
|
||||
</td>
|
||||
<td>
|
||||
<a href="{% url 'management:edit_orthomosaic' ortho.id %}">{{ ortho.name }}</a>
|
||||
</td>
|
||||
<td><a href="{% url 'management:remove_orthomosaic' ortho.id %}" class="btn btn-danger btn-block btn-sm"><i class="fa fa-trash"></i> Удалить</a></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div> <!-- /.card-body -->
|
||||
</div>
|
||||
<!-- /.nav-tabs-custom -->
|
||||
</div>
|
||||
<!-- /.col -->
|
||||
</div>
|
||||
<!-- /.row -->
|
||||
</div><!-- /.container-fluid -->
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@ -40,7 +40,7 @@
|
||||
</section>
|
||||
|
||||
<section class="content">
|
||||
<form autocomplete="off" method="post" enctype="multipart/form-data" class="form-horizontal">
|
||||
<form autocomplete="off" method="post" class="form-horizontal">
|
||||
{% csrf_token %}
|
||||
<div class="container-fluid">
|
||||
<div class="row">
|
||||
@ -49,7 +49,7 @@
|
||||
<div class="card">
|
||||
<div class="card-header">Удаление ортофотоплана</div>
|
||||
<div class="card-body">
|
||||
<p>Вы уверены, что хотите удалить ортофотоплан?</p>
|
||||
<p>Вы уверены, что хотите удалить ортофотоплан: {{ object.name }}?</p>
|
||||
</div><!-- /.card-body -->
|
||||
<div class="card-footer">
|
||||
<button id="btnok" type="submit" class="btn bg-gradient-danger">Удалить</button>
|
||||
@ -48,23 +48,10 @@
|
||||
</div> <!-- /.card-header -->
|
||||
<div class="card-body">
|
||||
<div class="form-group row">
|
||||
<label for="id_prgr" class="col-sm-1 col-form-label">Файл с границами ПРГР ( .kml )
|
||||
: </label>
|
||||
<div class="col-sm-4">
|
||||
<label for="id_prgr" class="file-upload-label">Выберите файл с расширением
|
||||
.kml </label><br>
|
||||
<span>Сейчас выбран: <a href="/{{ prgr }}">{{ prgr }}</a></span>
|
||||
<input type="file" name="prgr" value='{{ prgr }}' class="form-control" autofocus=""
|
||||
id="id_prgr" style="visibility:hidden;" accept=".kml">
|
||||
</div>
|
||||
<a href="{% url 'management:manage_orthomosaic' %}" class="btn bg-gradient-primary">Ортофотопланы</a>
|
||||
</div>
|
||||
<div class="form-group row">
|
||||
<a href="{% url 'add_orthomosaic' %}" class="btn bg-gradient-primary">Загрузить
|
||||
ортофотоплан</a>
|
||||
</div>
|
||||
<div class="form-group row">
|
||||
<a href="{% url 'remove_orthomosaic' %}" class="btn bg-gradient-danger">Удалить
|
||||
ортофотоплан</a>
|
||||
<a href="{% url 'management:manage_icons' %}" class="btn bg-gradient-primary">Изображения</a>
|
||||
</div>
|
||||
</div> <!-- /.card-body -->
|
||||
<div class="card-footer">
|
||||
@ -426,9 +413,9 @@
|
||||
<label for="icon_{{ gto_icon.id }}" class="file-upload-label">Выберите
|
||||
изображение</label><br>
|
||||
<span>Сейчас выбран: <a
|
||||
href="/{{ gto_icon.path }}">/{{ gto_icon.path }}</a></span>
|
||||
href="{{ gto_icon.icon.url }}">{{ gto_icon.icon.url }}</a></span>
|
||||
<input type="file" name="{{ gto_icon.model }}"
|
||||
value='/{{ gto_icon.path }}'
|
||||
value='{{ gto_icon.icon.url }}'
|
||||
class="form-control autosubmit" autofocus=""
|
||||
form="gto_icon_save"
|
||||
id="icon_{{ gto_icon.id }}" style="visibility:hidden;"
|
||||
@ -436,8 +423,10 @@
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
<a href="{% url 'gto_icon_add' %}" class="btn bg-gradient-primary">Добавить
|
||||
изображение</a>
|
||||
<a href="{% url 'management:add_gto_icon' %}"
|
||||
class="btn bg-gradient-primary">
|
||||
Добавить изображение
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -657,7 +646,7 @@
|
||||
function delete_user(id) {
|
||||
var Rec = $.ajax({
|
||||
method: 'POST',
|
||||
url: window.location.pathname + 'user/delete/',
|
||||
url: window.location.icon.image.urlname + 'user/delete/',
|
||||
async: true,
|
||||
data: {
|
||||
id: id,
|
||||
|
||||
@ -1,24 +1,41 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from django.conf.urls import ( # Используйте include() чтобы добавлять URL из каталога приложения
|
||||
include, url)
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.urls import path
|
||||
|
||||
from apps.management.views import views_management, views_user
|
||||
from apps.management.views.views_settings import add_orthomosaic, gto_icon_add, remove_orthomosaic
|
||||
from apps.management.views.views_settings import (
|
||||
add_gto_icon,
|
||||
|
||||
manage_orthomosaic,
|
||||
add_orthomosaic,
|
||||
edit_orthomosaic,
|
||||
remove_orthomosaic,
|
||||
|
||||
manage_icon,
|
||||
add_icon,
|
||||
edit_icon,
|
||||
remove_icon,
|
||||
)
|
||||
|
||||
app_name = "management"
|
||||
|
||||
urlpatterns = [
|
||||
url(r"^$", views_management.main_index, name="main_index"),
|
||||
url(r"^gto_icon_add/$", gto_icon_add, name="gto_icon_add"),
|
||||
url(r"add_orthomosaic/$", add_orthomosaic, name="add_orthomosaic"),
|
||||
url(r"remove_orthomosaic/$", remove_orthomosaic, name="remove_orthomosaic"),
|
||||
url(r"^user/add/$", views_user.user_add, name="user_add"),
|
||||
url(r"^user/$", views_user.user_edit, name="user_edit"),
|
||||
url(r"^user/password/$", views_user.user_password_edit, name="user_password_edit"),
|
||||
url(
|
||||
r"^user/password/save/$",
|
||||
views_user.user_password_save,
|
||||
name="user_password_save",
|
||||
),
|
||||
url(r"^user/save/$", views_user.user_save, name="user_save"),
|
||||
url(r"^user/delete/$", views_user.user_delete, name="user_delete"),
|
||||
path("", views_management.main_index, name="main_index"),
|
||||
|
||||
path("gto_icon/add/", add_gto_icon, name="add_gto_icon"),
|
||||
path("orthomosaic/", manage_orthomosaic, name="manage_orthomosaic"),
|
||||
path("orthomosaic/create/", add_orthomosaic, name="add_orthomosaic"),
|
||||
path("orthomosaic/<int:pk>/edit/", edit_orthomosaic, name="edit_orthomosaic"),
|
||||
path("orthomosaic/<int:pk>/remove/", remove_orthomosaic, name="remove_orthomosaic"),
|
||||
|
||||
path("icons/", manage_icon, name="manage_icons"),
|
||||
path("icons/create/", add_icon, name="add_icon"),
|
||||
path("icons/<int:pk>/edit/", edit_icon, name="edit_icon"),
|
||||
path("icons/<int:pk>/remove/", remove_icon, name="remove_icon"),
|
||||
|
||||
path("user/add/", views_user.user_add, name="user_add"),
|
||||
path("user/", views_user.user_edit, name="user_edit"),
|
||||
path("user/password/", views_user.user_password_edit, name="user_password_edit"),
|
||||
path("user/password/save/", views_user.user_password_save, name="user_password_save"),
|
||||
path("user/save/", views_user.user_save, name="user_save"),
|
||||
path("user/delete/", views_user.user_delete, name="user_delete"),
|
||||
]
|
||||
|
||||
55
apps/management/views/generate_tiles.py
Normal file
@ -0,0 +1,55 @@
|
||||
import subprocess
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
from osgeo import gdal
|
||||
|
||||
from sabron.util import logging
|
||||
|
||||
|
||||
def has_srs(raster_path: str) -> bool:
|
||||
try:
|
||||
ds = gdal.Open(raster_path)
|
||||
return bool(ds.GetProjection())
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def generate_tiles(input_file: str, output_folder: str, srs: str = "EPSG:4326") -> None:
|
||||
gdal.UseExceptions()
|
||||
|
||||
try:
|
||||
# Проверяем, есть ли встроенная SRS
|
||||
if has_srs(input_file):
|
||||
tile_input = input_file
|
||||
else:
|
||||
# Создаём .vrt с заданной системой координат
|
||||
vrt_path = input_file + ".vrt"
|
||||
translate_cmd = [
|
||||
"gdal_translate",
|
||||
"-of", "VRT",
|
||||
"-a_srs", srs,
|
||||
input_file,
|
||||
vrt_path
|
||||
]
|
||||
subprocess.run(translate_cmd, check=True)
|
||||
tile_input = vrt_path
|
||||
|
||||
# Генерация тайлов
|
||||
cmd = [
|
||||
sys.executable,
|
||||
"-m", "osgeo_utils.gdal2tiles",
|
||||
"-z", "2-16",
|
||||
"--webviewer=none",
|
||||
"--xyz",
|
||||
"--processes=4",
|
||||
tile_input,
|
||||
output_folder,
|
||||
]
|
||||
subprocess.run(cmd, check=True)
|
||||
|
||||
except subprocess.CalledProcessError:
|
||||
logging.error(traceback.format_exc())
|
||||
except Exception:
|
||||
logging.error("Unexpected error during tile generation")
|
||||
logging.error(traceback.format_exc())
|
||||
102
apps/management/views/util.py
Normal file
@ -0,0 +1,102 @@
|
||||
import multiprocessing
|
||||
import os
|
||||
import tempfile
|
||||
import uuid
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.gis.gdal import GDALRaster
|
||||
from osgeo import osr, gdal
|
||||
|
||||
from apps.main.models.model_static_layer import orthos_path
|
||||
from apps.management.views.generate_tiles import generate_tiles
|
||||
|
||||
|
||||
def get_extent(rst: GDALRaster, is_png: bool = False) -> tuple[float, float, float, float]:
|
||||
gdal.UseExceptions()
|
||||
rst_extent = rst.extent # (min_x, min_y, max_x, max_y)
|
||||
if is_png:
|
||||
return rst_extent
|
||||
if rst.srid == 4326:
|
||||
return rst.extent
|
||||
source_srs = osr.SpatialReference()
|
||||
if rst.srs:
|
||||
source_srs.ImportFromWkt(rst.srs.wkt)
|
||||
else:
|
||||
source_srs.ImportFromEPSG(3857)
|
||||
|
||||
target_srs = osr.SpatialReference()
|
||||
target_srs.ImportFromEPSG(4326)
|
||||
|
||||
try:
|
||||
transform = osr.CoordinateTransformation(source_srs, target_srs)
|
||||
except Exception as e: # noqa: B902
|
||||
raise ValueError(f"Ошибка создания преобразователя координат: {str(e)}")
|
||||
|
||||
try:
|
||||
min_lat, min_lon, _ = transform.TransformPoint(rst_extent[0], rst_extent[1])
|
||||
|
||||
max_lat, max_lon, _ = transform.TransformPoint(rst_extent[2], rst_extent[3])
|
||||
except Exception as e: # noqa: B902
|
||||
raise ValueError(f"Ошибка преобразования координат: {str(e)}")
|
||||
|
||||
return (min_lon, min_lat, max_lon, max_lat)
|
||||
|
||||
|
||||
def save_tif(uploaded_file, obj):
|
||||
# Сохраняем файл во временное хранилище
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=".tif") as tmp:
|
||||
for chunk in uploaded_file.chunks():
|
||||
tmp.write(chunk)
|
||||
tmp_path = tmp.name
|
||||
|
||||
rst = GDALRaster(tmp_path, write=False)
|
||||
extent = get_extent(rst)
|
||||
|
||||
ortho_uuid = str(uuid.uuid4())
|
||||
save_path = os.path.join(orthos_path, ortho_uuid)
|
||||
os.makedirs(save_path, exist_ok=True)
|
||||
|
||||
obj.min_lon = extent[0]
|
||||
obj.min_lat = extent[1]
|
||||
obj.max_lon = extent[2]
|
||||
obj.max_lat = extent[3]
|
||||
obj.url = f"{settings.MEDIA_URL}map/orthos/{ortho_uuid}/{{z}}/{{x}}/{{y}}.png"
|
||||
obj.layer_type = "Tile"
|
||||
obj.save()
|
||||
|
||||
process = multiprocessing.Process(target=generate_tiles, args=(tmp_path, save_path))
|
||||
process.start()
|
||||
|
||||
|
||||
def save_png(uploaded_image, uploaded_ext_file, obj):
|
||||
# Сохраняем PNG во временный файл
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp_image:
|
||||
for chunk in uploaded_image.chunks():
|
||||
tmp_image.write(chunk)
|
||||
tmp_image_path = tmp_image.name
|
||||
|
||||
# Сохраняем PNGW рядом с PNG
|
||||
pngw_path = tmp_image_path + "w" # GDAL ожидает .pngw рядом
|
||||
with open(pngw_path, "wb") as tmp_world:
|
||||
for chunk in uploaded_ext_file.chunks():
|
||||
tmp_world.write(chunk)
|
||||
|
||||
# Загружаем через GDALRaster для получения extent
|
||||
rst = GDALRaster(tmp_image_path, write=False)
|
||||
extent = get_extent(rst, is_png=True)
|
||||
|
||||
ortho_uuid = str(uuid.uuid4())
|
||||
save_path = os.path.join(orthos_path, ortho_uuid)
|
||||
os.makedirs(save_path, exist_ok=True)
|
||||
|
||||
obj.min_lon = extent[0]
|
||||
obj.min_lat = extent[1]
|
||||
obj.max_lon = extent[2]
|
||||
obj.max_lat = extent[3]
|
||||
obj.url = f"{settings.MEDIA_URL}map/orthos/{ortho_uuid}/{{z}}/{{x}}/{{y}}.png"
|
||||
obj.layer_type = "Tile"
|
||||
obj.save()
|
||||
|
||||
# Передаём файл в генератор тайлов
|
||||
process = multiprocessing.Process(target=generate_tiles, args=(tmp_image_path, save_path))
|
||||
process.start()
|
||||
@ -22,15 +22,6 @@ from . import views_settings
|
||||
@never_cache
|
||||
def main_index(request):
|
||||
try:
|
||||
|
||||
# if request.user.profile.role !=1 or request.user.profile.role !=2:
|
||||
# return redirect('/')
|
||||
param = request.GET.dict()
|
||||
if "module" in param:
|
||||
if param["module"] == "settings":
|
||||
return views_settings.main_index(request)
|
||||
return views_settings.main_index(request)
|
||||
context = generalmodule.get_context_template()
|
||||
return render(request, "main_management.html", context)
|
||||
except Exception as err:
|
||||
logging.error(traceback.format_exc())
|
||||
|
||||
@ -1,25 +1,22 @@
|
||||
import os
|
||||
import shutil
|
||||
import traceback
|
||||
import uuid
|
||||
import zipfile
|
||||
from datetime import datetime
|
||||
|
||||
from django import forms
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.contrib.auth.models import User
|
||||
from django.core import exceptions
|
||||
from django.core.files.uploadedfile import InMemoryUploadedFile
|
||||
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
|
||||
from django.db.models import Q
|
||||
from django.shortcuts import redirect, render
|
||||
from django.shortcuts import redirect, render, get_object_or_404
|
||||
from django.views.decorators.cache import never_cache
|
||||
|
||||
from apps.general.models.model_settings import Settings
|
||||
from apps.general.views import settingsmodule
|
||||
from apps.geoproc.models.model_sector import Sector
|
||||
from apps.gto.models.model_type_icons import ModelTypeIcons
|
||||
from apps.main.models.model_icons import Icons
|
||||
from apps.main.models.model_static_layer import StaticLayer
|
||||
from apps.management.forms.gto_icon import ModelTypeIconsForm
|
||||
from apps.management.forms.icon import IconForm
|
||||
from apps.management.forms.orthomosaic import OrthomosaicForm
|
||||
from apps.management.views import views_user
|
||||
from apps.management.views.util import save_tif, save_png
|
||||
from apps.util import generalmodule
|
||||
from sabron.util import logging
|
||||
|
||||
@ -57,7 +54,7 @@ def rtls_save(request):
|
||||
rtls_password_link.value = post_param["rtls_password"]
|
||||
rtls_password_link.save()
|
||||
return redirect("/management/?module=settings")
|
||||
except Exception as err:
|
||||
except Exception:
|
||||
logging.error(traceback.format_exc())
|
||||
return redirect("/management/")
|
||||
|
||||
@ -85,7 +82,7 @@ def oset_save(request):
|
||||
element_link.save()
|
||||
|
||||
return redirect("/management/?module=settings")
|
||||
except Exception as err:
|
||||
except Exception:
|
||||
logging.error(traceback.format_exc())
|
||||
return redirect("/management/")
|
||||
|
||||
@ -122,7 +119,7 @@ def file_save(request):
|
||||
setting.value = save_path
|
||||
setting.save()
|
||||
return redirect("/management/?module=settings")
|
||||
except Exception as err:
|
||||
except Exception:
|
||||
logging.error(traceback.format_exc())
|
||||
return redirect("/management/")
|
||||
|
||||
@ -135,54 +132,38 @@ def gto_icon_save(request):
|
||||
file_obj = request.FILES[file]
|
||||
save_path = os.path.join("media/map/gto", file_obj.name)
|
||||
|
||||
# Убедитесь, что директория существует
|
||||
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
||||
|
||||
# Открываем файл для записи
|
||||
with open(save_path, "wb") as destination:
|
||||
for chunk in file_obj.chunks():
|
||||
destination.write(chunk)
|
||||
|
||||
icon = ModelTypeIcons.objects.filter(model=file).first()
|
||||
if icon is None:
|
||||
ModelTypeIcons.objects.create(model=file, path=save_path)
|
||||
ModelTypeIcons.objects.create(model=file, icon=file_obj)
|
||||
else:
|
||||
icon.path = save_path
|
||||
icon.icon = file_obj
|
||||
icon.save()
|
||||
return redirect("/management/?module=settings")
|
||||
except Exception as err:
|
||||
except Exception:
|
||||
logging.error(traceback.format_exc())
|
||||
return redirect("/management/")
|
||||
|
||||
|
||||
@login_required(login_url="/")
|
||||
@never_cache
|
||||
def gto_icon_add(request):
|
||||
def add_gto_icon(request):
|
||||
try:
|
||||
if request.method == "GET":
|
||||
return render(request, "icon_add.html")
|
||||
if request.method == "POST":
|
||||
file_obj = request.FILES["icon"]
|
||||
model = request.POST["model"]
|
||||
save_path = os.path.join("media/map/gto", file_obj.name)
|
||||
form = ModelTypeIconsForm(request.POST, request.FILES)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect("/management/?module=settings")
|
||||
else:
|
||||
form = ModelTypeIconsForm()
|
||||
|
||||
# Убедитесь, что директория существует
|
||||
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
||||
|
||||
# Открываем файл для записи
|
||||
with open(save_path, "wb") as destination:
|
||||
for chunk in file_obj.chunks():
|
||||
destination.write(chunk)
|
||||
|
||||
icon = ModelTypeIcons.objects.filter(model=model).first()
|
||||
if icon is None:
|
||||
ModelTypeIcons.objects.create(model=model, path=save_path)
|
||||
else:
|
||||
icon.path = save_path
|
||||
icon.save()
|
||||
|
||||
return redirect("/management/?module=settings")
|
||||
except Exception as err:
|
||||
return render(request, "icon_add.html", {'form': form})
|
||||
except Exception:
|
||||
logging.error(traceback.format_exc())
|
||||
return redirect("/management/")
|
||||
|
||||
@ -206,114 +187,163 @@ def main_index(request):
|
||||
return gto_icon_save(request)
|
||||
context = generalmodule.get_context_template()
|
||||
return render(request, "settings.html", context)
|
||||
except Exception as err:
|
||||
except Exception:
|
||||
logging.error(traceback.format_exc())
|
||||
return redirect("/management/")
|
||||
|
||||
|
||||
@login_required(login_url="/")
|
||||
@never_cache
|
||||
def remove_orthomosaic(request):
|
||||
def manage_orthomosaic(request):
|
||||
try:
|
||||
if request.method == "GET":
|
||||
context = generalmodule.get_context_template()
|
||||
return render(request, "remove_orthomosaic.html", context)
|
||||
if request.method == "POST":
|
||||
shutil.rmtree("media/map/orth")
|
||||
return redirect("/management/")
|
||||
except Exception as err:
|
||||
context = generalmodule.get_context_template()
|
||||
tile_layers = StaticLayer.objects.filter(layer_type="Tile")
|
||||
context["catalog"] = tile_layers
|
||||
return render(request, "orthomosaic/manage_orthomosaic.html", context)
|
||||
except Exception:
|
||||
logging.error(traceback.format_exc())
|
||||
return redirect("/management/")
|
||||
|
||||
|
||||
@login_required(login_url="/")
|
||||
@never_cache
|
||||
def add_orthomosaic(request):
|
||||
try:
|
||||
minLon = settingsmodule.get_settings("orth_minLon", "")
|
||||
minLat = settingsmodule.get_settings("orth_minLat", "")
|
||||
maxLon = settingsmodule.get_settings("orth_maxLon", "")
|
||||
maxLat = settingsmodule.get_settings("orth_maxLat", "")
|
||||
|
||||
context = generalmodule.get_context_template()
|
||||
if request.method == "GET":
|
||||
context = generalmodule.get_context_template()
|
||||
return render(request, "add_orthomosaic.html", context)
|
||||
form = OrthomosaicForm()
|
||||
context["form"] = form
|
||||
return render(request, "orthomosaic/form_orthomosaic.html", context)
|
||||
if request.method == "POST":
|
||||
settingsmodule.set_settings(
|
||||
"orth_minLon", request.POST["min_lon"].replace(",", ".")
|
||||
)
|
||||
settingsmodule.set_settings(
|
||||
"orth_minLat", request.POST["min_lat"].replace(",", ".")
|
||||
)
|
||||
settingsmodule.set_settings(
|
||||
"orth_maxLon", request.POST["max_lon"].replace(",", ".")
|
||||
)
|
||||
settingsmodule.set_settings(
|
||||
"orth_maxLat", request.POST["max_lat"].replace(",", ".")
|
||||
)
|
||||
|
||||
# Получаем архив из запроса
|
||||
archive = request.FILES["archive"]
|
||||
# Путь для извлечения
|
||||
path = "media/map/orth/tiles"
|
||||
|
||||
# Удаляем целевую директорию, если она существует
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
|
||||
# Создаем целевую директорию, если её нет
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
# Если архив загружен в память (InMemoryUploadedFile), сохраняем его на диск
|
||||
if isinstance(archive, InMemoryUploadedFile):
|
||||
temp_archive_path = os.path.join(path, "temp_archive.zip")
|
||||
with open(temp_archive_path, "wb") as temp_archive:
|
||||
for chunk in archive.chunks():
|
||||
temp_archive.write(chunk)
|
||||
archive_path = temp_archive_path
|
||||
form = OrthomosaicForm(request.POST, request.FILES)
|
||||
if form.is_valid():
|
||||
obj = form.save(commit=False)
|
||||
tif_uploaded = bool(form.cleaned_data.get("tif_image"))
|
||||
png_uploaded = all(
|
||||
[bool(form.cleaned_data.get("png_image")), bool("png_ext_file")]
|
||||
)
|
||||
if tif_uploaded:
|
||||
save_tif(form.cleaned_data.get("tif_image"), obj)
|
||||
elif png_uploaded:
|
||||
save_png(
|
||||
form.cleaned_data.get("png_image"),
|
||||
form.cleaned_data.get("png_ext_file"),
|
||||
obj,
|
||||
)
|
||||
return redirect("management:manage_orthomosaic")
|
||||
else:
|
||||
# Если архив уже на диске, используем его путь
|
||||
archive_path = archive.temporary_file_path()
|
||||
|
||||
# Распаковываем архив, игнорируя префикс `tiles/`
|
||||
with zipfile.ZipFile(archive_path, "r") as zip_ref:
|
||||
# Получаем список всех файлов в архиве
|
||||
file_list = zip_ref.namelist()
|
||||
|
||||
# Выводим список файлов для отладки
|
||||
#for file in file_list:
|
||||
# print(file)
|
||||
|
||||
# Префикс, который нужно игнорировать (в вашем случае `tiles/`)
|
||||
prefix_to_remove = "tiles/"
|
||||
|
||||
# Извлекаем все файлы, начиная с префикса `tiles/`
|
||||
for file in file_list:
|
||||
if file.startswith(prefix_to_remove):
|
||||
# Создаем новый путь без префикса `tiles/`
|
||||
new_file_path = os.path.join(
|
||||
path, os.path.relpath(file, prefix_to_remove)
|
||||
)
|
||||
|
||||
# Если это каталог, создаем его
|
||||
if file.endswith("/"):
|
||||
print(f"Creating directory: {new_file_path}")
|
||||
os.makedirs(new_file_path, exist_ok=True)
|
||||
else:
|
||||
# Извлекаем файл в нужный путь
|
||||
print(f"Extracting: {file} -> {new_file_path}")
|
||||
# Создаем родительский каталог, если он не существует
|
||||
os.makedirs(os.path.dirname(new_file_path), exist_ok=True)
|
||||
# Извлекаем файл
|
||||
with zip_ref.open(file) as source_file:
|
||||
with open(new_file_path, "wb") as target_file:
|
||||
shutil.copyfileobj(source_file, target_file)
|
||||
|
||||
# Удаляем временный архив, если он был создан
|
||||
if isinstance(archive, InMemoryUploadedFile):
|
||||
os.remove(archive_path)
|
||||
|
||||
return redirect("/management/?module=settings")
|
||||
|
||||
except Exception as err:
|
||||
context["form"] = form
|
||||
return render(request, "orthomosaic/form_orthomosaic.html", context)
|
||||
except Exception:
|
||||
logging.error(traceback.format_exc())
|
||||
return redirect("/management/")
|
||||
|
||||
|
||||
@login_required(login_url="/")
|
||||
@never_cache
|
||||
def edit_orthomosaic(request, pk):
|
||||
try:
|
||||
if request.method == "GET":
|
||||
obj = get_object_or_404(StaticLayer, id=pk)
|
||||
context = generalmodule.get_context_template()
|
||||
form = OrthomosaicForm(instance=obj)
|
||||
context["form"] = form
|
||||
return render(request, "orthomosaic/form_orthomosaic.html", context)
|
||||
if request.method == "POST":
|
||||
obj = get_object_or_404(StaticLayer, id=pk)
|
||||
form = OrthomosaicForm(request.POST, instance=obj)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect("management:manage_orthomosaic")
|
||||
except Exception:
|
||||
logging.error(traceback.format_exc())
|
||||
return redirect("management:manage_orthomosaic")
|
||||
|
||||
|
||||
@login_required(login_url="/")
|
||||
@never_cache
|
||||
def remove_orthomosaic(request, pk):
|
||||
try:
|
||||
if request.method == "GET":
|
||||
obj = get_object_or_404(StaticLayer, id=pk)
|
||||
context = generalmodule.get_context_template()
|
||||
context["object"] = obj
|
||||
return render(request, "orthomosaic/remove_orthomosaic.html", context)
|
||||
if request.method == "POST":
|
||||
obj = get_object_or_404(StaticLayer, id=pk)
|
||||
obj.delete()
|
||||
return redirect("management:manage_orthomosaic")
|
||||
except Exception:
|
||||
logging.error(traceback.format_exc())
|
||||
return redirect("management:manage_orthomosaic")
|
||||
|
||||
|
||||
@login_required(login_url="/")
|
||||
@never_cache
|
||||
def manage_icon(request):
|
||||
try:
|
||||
context = generalmodule.get_context_template()
|
||||
icons = Icons.objects.all()
|
||||
context["catalog"] = icons
|
||||
return render(request, "icons/manage_icon.html", context)
|
||||
except Exception:
|
||||
logging.error(traceback.format_exc())
|
||||
|
||||
|
||||
@login_required(login_url="/")
|
||||
@never_cache
|
||||
def add_icon(request):
|
||||
try:
|
||||
context = generalmodule.get_context_template()
|
||||
if request.method == "GET":
|
||||
form = IconForm()
|
||||
context["form"] = form
|
||||
return render(request, "icons/form_icon.html",
|
||||
context)
|
||||
if request.method == "POST":
|
||||
form = IconForm(request.POST, request.FILES)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect("management:manage_icons")
|
||||
else:
|
||||
context["form"] = form
|
||||
return render(request, "icons/form_icon.html",
|
||||
context)
|
||||
except Exception:
|
||||
logging.error(traceback.format_exc())
|
||||
|
||||
|
||||
@login_required(login_url="/")
|
||||
@never_cache
|
||||
def edit_icon(request, pk):
|
||||
try:
|
||||
if request.method == "GET":
|
||||
obj = get_object_or_404(Icons, id=pk)
|
||||
context = generalmodule.get_context_template()
|
||||
form = IconForm(instance=obj)
|
||||
context["form"] = form
|
||||
return render(request, "icons/form_icon.html", context)
|
||||
if request.method == "POST":
|
||||
obj = get_object_or_404(Icons, id=pk)
|
||||
form = IconForm(request.POST, request.FILES, instance=obj)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect("management:manage_icons")
|
||||
except Exception:
|
||||
logging.error(traceback.format_exc())
|
||||
|
||||
|
||||
@login_required(login_url="/")
|
||||
@never_cache
|
||||
def remove_icon(request, pk):
|
||||
try:
|
||||
if request.method == "GET":
|
||||
obj = get_object_or_404(Icons, id=pk)
|
||||
context = generalmodule.get_context_template()
|
||||
context["object"] = obj
|
||||
return render(request, "icons/remove_icon.html", context)
|
||||
if request.method == "POST":
|
||||
obj = get_object_or_404(Icons, id=pk)
|
||||
obj.delete()
|
||||
return redirect("management:manage_icons")
|
||||
except Exception:
|
||||
logging.error(traceback.format_exc())
|
||||
return redirect("management:manage_icons")
|
||||
|
||||
@ -5,6 +5,5 @@ from apps.workerslocation.models.workers_locations import WorkersLocation
|
||||
|
||||
@admin.register(WorkersLocation)
|
||||
class WorkersLocationAdmin(admin.ModelAdmin):
|
||||
list_display = (
|
||||
"uid", "latitude", "longitude", "velocity", "radius", "update_time",
|
||||
)
|
||||
list_display = ("name", "uid", "icon")
|
||||
list_editable = ("icon",)
|
||||
|
||||
@ -9,8 +9,10 @@ class WorkerForm(forms.ModelForm):
|
||||
self.fields["name"].widget.attrs.update(
|
||||
{"class": "form-control", "placeholder": "Наименование"}
|
||||
)
|
||||
self.fields["icon"].widget.attrs.update(
|
||||
{"class": "form-control"}
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = WorkersLocation
|
||||
fields = ('name',)
|
||||
|
||||
fields = ("name", "icon")
|
||||
|
||||
20
apps/workerslocation/migrations/0009_workerslocation_icon.py
Normal file
@ -0,0 +1,20 @@
|
||||
# Generated by Django 3.2.25 on 2025-05-15 04:14
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('main', '0011_auto_20250515_0414'),
|
||||
('workerslocation', '0008_workerslocation_name'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='workerslocation',
|
||||
name='icon',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='workers', to='main.icons', verbose_name='Иконка'),
|
||||
),
|
||||
]
|
||||
@ -1,5 +1,7 @@
|
||||
from django.db import models
|
||||
|
||||
from apps.main.models.model_icons import Icons
|
||||
|
||||
|
||||
class WorkersLocation(models.Model):
|
||||
name = models.CharField(max_length=128, verbose_name="Наименование", blank=True, null=True)
|
||||
@ -19,6 +21,15 @@ class WorkersLocation(models.Model):
|
||||
update_time = models.DateTimeField(verbose_name="Время связи", blank=True, null=True)
|
||||
active = models.BooleanField(default=True)
|
||||
|
||||
icon = models.ForeignKey(
|
||||
Icons,
|
||||
on_delete=models.SET_NULL,
|
||||
verbose_name="Иконка",
|
||||
blank=True,
|
||||
null=True,
|
||||
related_name='workers'
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return self.name if self.name else self.uid
|
||||
|
||||
|
||||
@ -24,7 +24,11 @@
|
||||
</div>
|
||||
<div class="col-sm-6">
|
||||
<ol class="breadcrumb float-sm-right">
|
||||
<li class="breadcrumb-item"><a href="{% url 'mainindex' %}">Главная</a>
|
||||
<li class="breadcrumb-item">
|
||||
<a href="{% url 'mainindex' %}">Главная</a>
|
||||
</li>
|
||||
<li class="breadcrumb-item">
|
||||
<a href="{% url 'workers_location:main_index' %}">Местоположение персонала</a>
|
||||
</li>
|
||||
<li class="breadcrumb-item active">Редактирование сотрудника</li>
|
||||
</ol>
|
||||
@ -47,15 +51,21 @@
|
||||
</div>
|
||||
<!-- form start -->
|
||||
<div class="card-body">
|
||||
<div class="form-group">
|
||||
<label for="name">Наименование</label>
|
||||
{{ form.name }}
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="uid">Идентификатор</label>
|
||||
<input type="text" id="uid" name="uid" readonly value="{{ worker.uid }}"
|
||||
class="form-control readonly">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="name">Наименование</label>
|
||||
{{ form.name }}
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="name">Изображение</label>
|
||||
{{ form.icon }}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="card-footer">
|
||||
<button type="submit" class="btn btn-primary">Сохранить</button>
|
||||
@ -122,39 +132,6 @@
|
||||
|
||||
mapCore.addLayer(workerLayer, 'dynamic');
|
||||
|
||||
const scanLayer = new ol.layer.Tile({
|
||||
source: new ol.source.XYZ({
|
||||
url: `/media/map/orth/tiles/{z}/{x}/{y}.png?seed=${Math.random() * 1000}`,
|
||||
}),
|
||||
extent: ol.proj.transformExtent(
|
||||
[
|
||||
parseFloat('{{ orth_minLon }}'),
|
||||
parseFloat('{{ orth_minLat }}'),
|
||||
parseFloat('{{ orth_maxLon }}'),
|
||||
parseFloat('{{ orth_maxLat }}')
|
||||
],
|
||||
'EPSG:4326', // Исходная проекция
|
||||
'EPSG:3857' // Целевая проекция
|
||||
)
|
||||
});
|
||||
scanLayer.set('title', 'Ортофотоплан')
|
||||
scanLayer.set('name', 'orto')
|
||||
mapCore.addLayer(scanLayer)
|
||||
|
||||
const mineBorderLayer = new ol.layer.Vector({
|
||||
source: new ol.source.Vector({
|
||||
url: '/{{ prgr }}',
|
||||
format: new ol.format.KML({extractStyles: false}),
|
||||
|
||||
}),
|
||||
style: polygonStyleFunction,
|
||||
});
|
||||
mineBorderLayer.set('title', 'Границы ПРГР')
|
||||
mineBorderLayer.set('name', 'prgr')
|
||||
|
||||
mapCore.addLayer(mineBorderLayer)
|
||||
|
||||
|
||||
// Инициализация статических слоев
|
||||
const createdLayersManager = new CreatedLayersManager({
|
||||
url: '{% url 'layers' %}',
|
||||
@ -166,7 +143,6 @@
|
||||
});
|
||||
|
||||
|
||||
|
||||
// Кнопка возврата
|
||||
document.getElementById('toStart').addEventListener('click', () => {
|
||||
mapCore.map.getView().animate({
|
||||
@ -178,7 +154,7 @@
|
||||
// Функция для обновления маркеров
|
||||
async function updateMarkers() {
|
||||
// Обновление работников
|
||||
const workersData = await fetch('{% url 'vlocation_update_object_with_id' worker.id %}')
|
||||
const workersData = await fetch('{% url 'workers_location:vlocation_update_object_with_id' worker.id %}')
|
||||
.then(r => r.json());
|
||||
|
||||
|
||||
|
||||
@ -122,39 +122,6 @@
|
||||
|
||||
mapCore.addLayer(workerLayer, 'dynamic');
|
||||
|
||||
const scanLayer = new ol.layer.Tile({
|
||||
source: new ol.source.XYZ({
|
||||
url: `/media/map/orth/tiles/{z}/{x}/{y}.png?seed=${Math.random() * 1000}`,
|
||||
}),
|
||||
extent: ol.proj.transformExtent(
|
||||
[
|
||||
parseFloat('{{ orth_minLon }}'),
|
||||
parseFloat('{{ orth_minLat }}'),
|
||||
parseFloat('{{ orth_maxLon }}'),
|
||||
parseFloat('{{ orth_maxLat }}')
|
||||
],
|
||||
'EPSG:4326', // Исходная проекция
|
||||
'EPSG:3857' // Целевая проекция
|
||||
)
|
||||
});
|
||||
scanLayer.set('title', 'Ортофотоплан')
|
||||
scanLayer.set('name', 'orto')
|
||||
mapCore.addLayer(scanLayer)
|
||||
|
||||
const mineBorderLayer = new ol.layer.Vector({
|
||||
source: new ol.source.Vector({
|
||||
url: '/{{ prgr }}',
|
||||
format: new ol.format.KML({extractStyles: false}),
|
||||
|
||||
}),
|
||||
style: polygonStyleFunction,
|
||||
});
|
||||
mineBorderLayer.set('title', 'Границы ПРГР')
|
||||
mineBorderLayer.set('name', 'prgr')
|
||||
|
||||
mapCore.addLayer(mineBorderLayer)
|
||||
|
||||
|
||||
// Инициализация статических слоев
|
||||
const createdLayersManager = new CreatedLayersManager({
|
||||
url: '{% url 'layers' %}',
|
||||
|
||||
@ -1,12 +1,13 @@
|
||||
from django.conf.urls import url
|
||||
from django.urls import path
|
||||
|
||||
from apps.workerslocation.views import views_main
|
||||
from apps.workerslocation.views.views_radiusapi import update_object, \
|
||||
worker_edit, update_worker_active
|
||||
|
||||
app_name = "workers_location"
|
||||
|
||||
urlpatterns = [
|
||||
url(r"^$", views_main.main_index, name="main_index"),
|
||||
path("", views_main.main_index, name="main_index"),
|
||||
path(
|
||||
"update_object/<int:pk>", update_object, name="vlocation_update_object_with_id"
|
||||
),
|
||||
|
||||
@ -77,6 +77,10 @@ def update_object(request, pk=None):
|
||||
for worker in workers:
|
||||
worker_name = worker.name if worker.name else worker.uid
|
||||
worker_connection_condition = get_worker_condition(worker.update_time)
|
||||
if worker.icon is not None:
|
||||
icon_path = worker.icon.image.url
|
||||
else:
|
||||
icon_path = None
|
||||
workers_mas.append(
|
||||
{
|
||||
"id": worker.id,
|
||||
@ -88,6 +92,7 @@ def update_object(request, pk=None):
|
||||
"iso_time": worker.update_time.isoformat(),
|
||||
"condition": worker_connection_condition,
|
||||
"active": worker.active,
|
||||
"icon": icon_path
|
||||
}
|
||||
)
|
||||
workers_mas.sort(key=lambda worker_: get_priority(worker_["name"]))
|
||||
|
||||
BIN
gdal/GDAL-3.6.2-cp310-cp310-win_amd64.whl
Normal file
|
Before Width: | Height: | Size: 5.5 KiB |
|
Before Width: | Height: | Size: 5.6 KiB |
|
Before Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 34 KiB |
|
Before Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 36 KiB |
|
Before Width: | Height: | Size: 59 KiB |
|
Before Width: | Height: | Size: 59 KiB |
|
Before Width: | Height: | Size: 5.7 KiB |
|
Before Width: | Height: | Size: 58 KiB |
|
Before Width: | Height: | Size: 74 KiB |
|
Before Width: | Height: | Size: 54 KiB |
|
Before Width: | Height: | Size: 88 KiB |
|
Before Width: | Height: | Size: 98 KiB |
|
Before Width: | Height: | Size: 113 KiB |
|
Before Width: | Height: | Size: 80 KiB |
|
Before Width: | Height: | Size: 31 KiB |
|
Before Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 4.4 KiB |
|
Before Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 6.2 KiB |
|
Before Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 90 KiB |
|
Before Width: | Height: | Size: 116 KiB |
|
Before Width: | Height: | Size: 135 KiB |
|
Before Width: | Height: | Size: 122 KiB |
|
Before Width: | Height: | Size: 130 KiB |
|
Before Width: | Height: | Size: 47 KiB |
|
Before Width: | Height: | Size: 29 KiB |
|
Before Width: | Height: | Size: 115 KiB |
|
Before Width: | Height: | Size: 127 KiB |
|
Before Width: | Height: | Size: 125 KiB |
|
Before Width: | Height: | Size: 113 KiB |
|
Before Width: | Height: | Size: 125 KiB |
|
Before Width: | Height: | Size: 122 KiB |
|
Before Width: | Height: | Size: 55 KiB |
|
Before Width: | Height: | Size: 63 KiB |
|
Before Width: | Height: | Size: 132 KiB |
|
Before Width: | Height: | Size: 99 KiB |
|
Before Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 62 KiB |
|
Before Width: | Height: | Size: 129 KiB |
|
Before Width: | Height: | Size: 109 KiB |
|
Before Width: | Height: | Size: 16 KiB |