lostplaces-backend/django_lostplaces/lostplaces/views/imports.py

92 lines
3.2 KiB
Python
Raw Permalink Normal View History

2022-10-16 10:14:04 +02:00
from django.views import View
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.utils.translation import gettext as _
from django.core.paginator import Paginator
from pykml import parser as kml_parser
from lostplaces.forms import UploadMapFileForm
from lostplaces.models import Place, PlaceImport
from lostplaces.views.base_views import (
IsSuperUserMixin
)
class UploadMapFileView(IsSuperUserMixin, View):
permission_denied_message = _('You are not allowed to import any places')
def get(self, request):
upload_form = UploadMapFileForm()
return render(request, 'import/upload_map_file.html', {'upload_form': upload_form})
def post(self, request):
upload_form = UploadMapFileForm(request.POST, request.FILES)
explorer = request.user.explorer
if upload_form.is_valid():
map_file = upload_form.cleaned_data['map_file']
parsed_kml = kml_parser.fromstring(map_file.read())
place_import = PlaceImport.objects.create(
explorer=request.user.explorer,
description=upload_form.cleaned_data['description']
)
for folder in parsed_kml.Document.Folder:
for place_kml in folder.Placemark:
lat_long = self.get_lat_long(place_kml)
name = str(place_kml.name) if hasattr(place_kml, 'name') else ''
description = str(place_kml.description) if hasattr(place_kml, 'description') else ''
place_model = Place.objects.create(
name=name.strip(),
latitude=lat_long[0],
longitude=lat_long[1],
description=description.strip(),
place_import=place_import,
mode='imported'
)
place_import.save()
return redirect(reverse('lostplaces_home'))
def get_lat_long(self, place_kml):
if hasattr(place_kml, 'Point') and len(place_kml.Point.coordinates) >= 1:
coordinates = str(place_kml.Point.coordinates[0]).strip()
splited = coordinates.split(',')
latitude = 0
longitude = 0
if len(splited) >= 1:
longitude = splited[0]
if len(splited) >= 2:
latitude = splited[1]
return (latitude, longitude)
else:
return (0, 0)
class ImportDetailView(IsSuperUserMixin, View):
permission_denied_message = _('You are not allowed to see this import\'s details')
def get_import(self):
return get_object_or_404(PlaceImport, pk=self.kwargs['pk'])
def get(self, request, *args, **kwargs):
place_import = self.get_import()
place_paginator = Paginator(place_import.place_list.all(), 18)
paginated_places = place_paginator.get_page(
request.GET.get('page')
)
context = {
'import': place_import,
'paginated_places': paginated_places,
'import_type': place_import.get_import_type_display()
}
return render(request, 'import/import_detail_view.html', context)