ref: remove multi-city support

This commit is contained in:
relikd
2024-07-28 00:57:38 +02:00
parent d0dd4e7925
commit 571d8fdb56
12 changed files with 48 additions and 230 deletions

View File

@@ -12,9 +12,3 @@ Start container with `docker-compose up -d` and create admin user (first-run):
```sh ```sh
docker-compose exec app python manage.py createsuperuser --email '' docker-compose exec app python manage.py createsuperuser --email ''
``` ```
Optionally, create an initial set of cities:
```sh
docker-compose exec app python manage.py loaddata initial_cities.json
```

View File

@@ -1,7 +1,7 @@
from django.contrib import admin from django.contrib import admin
from django.contrib.auth.models import Group # , User from django.contrib.auth.models import Group # , User
from app.models import City, Place from app.models import Place
# admin.site.register(Place, ) # admin.site.register(Place, )
@@ -21,21 +21,8 @@ admin.site.unregister(Group)
# App adjustments # App adjustments
############################# #############################
@admin.register(City)
class CityAdmin(admin.ModelAdmin):
list_display = ['name', 'place_count', 'center', 'zoom']
def get_readonly_fields(self, request, obj=None):
return ['name'] if obj else []
@admin.display(description='Orte')
def place_count(self, instance: 'City'):
return instance.places.count()
@admin.register(Place) @admin.register(Place)
class PlaceAdmin(admin.ModelAdmin): class PlaceAdmin(admin.ModelAdmin):
list_display = ['address', 'city', 'since', 'until', 'created', 'updated'] list_display = ['address', 'since', 'until', 'created', 'updated']
list_filter = ['city']
search_fields = ['address', 'description'] search_fields = ['address', 'description']
ordering = ['-updated'] ordering = ['-updated']

View File

@@ -1,10 +0,0 @@
[
{
"model": "app.city",
"fields": {
"name": "Berlin",
"center": "52.52, 13.40",
"zoom": 12
}
}
]

View File

@@ -0,0 +1,22 @@
# Generated by Django 4.2.13 on 2024-07-27 23:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='place',
name='city',
),
migrations.DeleteModel(
name='City',
),
migrations.RunSQL(
"UPDATE app_place SET img = 'img/'||id||'.jpg' WHERE img != '';"),
]

View File

@@ -1,2 +1 @@
from .city import City # noqa: F401
from .place import Place # noqa: F401 from .place import Place # noqa: F401

View File

@@ -1,85 +0,0 @@
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.db.models.signals import post_delete
from django.dispatch import receiver
from django.template.defaultfilters import slugify
import json
import shutil
from pathlib import Path
from map_location.fields import LocationField
import typing
if typing.TYPE_CHECKING:
from app.models.place import Place
class City(models.Model):
name = models.CharField('Name', max_length=100)
center = LocationField('Zentrum', options={
'markerZoom': 12,
})
zoom = models.IntegerField('Zoom', validators=[
MinValueValidator(4), MaxValueValidator(18)])
places: 'models.QuerySet[Place]'
class Meta:
verbose_name = 'Stadt'
verbose_name_plural = 'Städte'
ordering = ['name']
def __str__(self) -> str:
return self.name
@property
def slug(self):
return slugify(self.name)
@property
def data_path(self) -> Path:
return settings.MEDIA_ROOT / str(self.pk)
@property
def data_url(self) -> str:
return f'{self.pk}'
def save(self, *args, **kwargs):
rv = super().save(*args, **kwargs)
City.update_cities_json()
return rv
def asJson(self) -> 'dict[str, str|list[float]|int|None]':
return {
'id': self.pk,
'slug': self.slug,
'name': self.name,
'zoom': self.zoom,
'loc': [round(self.center.lat, 6),
round(self.center.long, 6)] if self.center else None,
}
def update_json(self):
rv = []
for place in self.places.all():
if not place.location or not place.isVacant:
continue
rv.append(place.asJson())
self.data_path.mkdir(parents=True, exist_ok=True)
with open(self.data_path / 'data.json', 'w') as fp:
json.dump(rv, fp)
@staticmethod
def update_cities_json():
cities_json = settings.MEDIA_ROOT / 'cities.json'
with open(cities_json, 'w') as fp:
json.dump([city.asJson() for city in City.objects.all()], fp)
@receiver(post_delete, sender=City)
def on_delete_City(sender, instance: 'City', using, **kwargs):
if instance.data_path.exists():
shutil.rmtree(instance.data_path, ignore_errors=True)
City.update_cities_json()

View File

@@ -1,8 +1,10 @@
from django.conf import settings
from django.db import models from django.db import models
from django.db.models.signals import post_delete from django.db.models.signals import post_delete
from django.dispatch import receiver from django.dispatch import receiver
import os import os
import json
from datetime import date from datetime import date
from map_location.fields import LocationField from map_location.fields import LocationField
@@ -10,28 +12,20 @@ from map_location.fields import LocationField
from app.fields import MonthField from app.fields import MonthField
from common.form.img_with_preview import ThumbnailImageField from common.form.img_with_preview import ThumbnailImageField
import typing
if typing.TYPE_CHECKING:
from app.models.city import City
def overwrite_img_upload(instance: 'Place', filename: str): def overwrite_img_upload(instance: 'Place', filename: str):
id = instance.pk or (Place.objects.count() + 1) id = instance.pk or (Place.objects.count() + 1)
path = instance.city.data_path / f'{id}.jpg' path = settings.MEDIA_ROOT / 'img' / f'{id}.jpg'
if path.is_file(): if path.is_file():
os.remove(path) os.remove(path)
return f'{instance.city.data_url}/{id}.jpg' return f'img/{id}.jpg'
class Place(models.Model): class Place(models.Model):
created = models.DateTimeField('Erstellt', auto_now_add=True) created = models.DateTimeField('Erstellt', auto_now_add=True)
updated = models.DateTimeField('Geändert', auto_now=True) updated = models.DateTimeField('Geändert', auto_now=True)
city: 'models.ForeignKey[City]' = models.ForeignKey(
'City', on_delete=models.CASCADE, related_name='places',
verbose_name='Stadt')
address = models.CharField('Adresse', max_length=100) address = models.CharField('Adresse', max_length=100)
img = ThumbnailImageField('Bild', blank=True, null=True, img = ThumbnailImageField('Bild', blank=True, null=True,
upload_to=overwrite_img_upload) # type: ignore upload_to=overwrite_img_upload) # type: ignore
@@ -65,7 +59,7 @@ class Place(models.Model):
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
rv = super().save(*args, **kwargs) rv = super().save(*args, **kwargs)
self.city.update_json() Place.update_json()
return rv return rv
def asJson(self) -> 'dict[str, str|list[float]|None]': def asJson(self) -> 'dict[str, str|list[float]|None]':
@@ -80,7 +74,13 @@ class Place(models.Model):
round(self.location.long, 6)] if self.location else None, round(self.location.long, 6)] if self.location else None,
} }
@staticmethod
def update_json():
with open(settings.MEDIA_ROOT / 'data.json', 'w') as fp:
json.dump([x.asJson() for x in Place.objects.all()
if x.location and x.isVacant], fp)
@receiver(post_delete, sender=Place) @receiver(post_delete, sender=Place)
def on_delete_Place(sender, instance: 'Place', using, **kwargs): def on_delete_Place(sender, instance: 'Place', using, **kwargs):
instance.city.update_json() Place.update_json()

View File

@@ -31,12 +31,7 @@
<img src="" alt="Kein Bild" /> <img src="" alt="Kein Bild" />
</div> </div>
</div> </div>
<div id="overlay"> <div id="overlay"><span id="city-counter" hidden></span></div>
<span id="city-counter" hidden></span>
<select id="city-select" hidden onchange="this.value ? showCity(this.value): showCityOverview()">
<option value="">-----</option>
</select>
</div>
<div id="map"></div> <div id="map"></div>
<script defer>start()</script> <script defer>start()</script>
</body> </body>

View File

@@ -1,7 +1,6 @@
const DATA_ROOT = '/data/'; const DATA_ROOT = '/data/';
let MAP = null; let MAP = null;
let LAYER = null; let LAYER = null;
let CITIES = {};
let PLACES = {}; let PLACES = {};
const DEFAULT_CENTER = [51.2, 9]; const DEFAULT_CENTER = [51.2, 9];
const DEFAULT_ZOOM = 6; const DEFAULT_ZOOM = 6;
@@ -15,16 +14,9 @@ async function loadJson(url) {
return await res.json(); return await res.json();
} }
async function loadCities() { async function loadData() {
CITIES = {};
for (const city of await loadJson(DATA_ROOT + 'cities.json')) {
CITIES[city.id] = city;
}
}
async function loadCity(cityId) {
PLACES = {}; PLACES = {};
for (const place of await loadJson(DATA_ROOT + cityId + '/data.json')) { for (const place of await loadJson(DATA_ROOT + 'data.json')) {
if (since(place.until) > 0) { if (since(place.until) > 0) {
continue; // not vacant anymore continue; // not vacant anymore
} }
@@ -37,15 +29,6 @@ async function loadCity(cityId) {
// Helper // Helper
// --------------------- // ---------------------
function getCityId(slug) {
for (const city of Object.values(CITIES)) {
if (city.slug === slug) {
return city.id;
}
}
return null;
}
function since(date) { function since(date) {
if (!date) { if (!date) {
return 0; return 0;
@@ -84,18 +67,6 @@ function closePopup(e) {
setPlace(null) setPlace(null)
} }
function makeCityMarker(city) {
return L.marker(L.latLng(city.loc), {
pid: city.id,
title: city.name,
icon: makeIcon('pin pin-city'),
}).on('click', cityPinClick);
}
async function cityPinClick(pin) {
await showCity(pin.target.options.pid);
}
// --------------------- // ---------------------
// UI updates // UI updates
// --------------------- // ---------------------
@@ -112,16 +83,10 @@ function setPlace(placeId) {
: place.since ? 'seit ' + place.since : '???'; : place.since ? 'seit ' + place.since : '???';
div.querySelector('#_desc').innerText = place.desc || ''; div.querySelector('#_desc').innerText = place.desc || '';
location.hash = location.hash.split('|')[0] + (hide ? '' : '|' + placeId); location.hash = hide ? '' : placeId;
document.title = document.title.split(' "', 1)[0] + (hide ? '' : ' "' + place.addr + '"'); document.title = document.title.split(' "', 1)[0] + (hide ? '' : ' "' + place.addr + '"');
} }
function setCity(city) {
document.getElementById('city-select').value = city ? city.id : '';
location.hash = city ? city.slug : '';
document.title = document.title.split(' in ', 1)[0] + (city ? ' in ' + city.name : '');
}
function updateCounter() { function updateCounter() {
const total = Object.keys(PLACES).length; const total = Object.keys(PLACES).length;
const counter = document.getElementById('city-counter'); const counter = document.getElementById('city-counter');
@@ -153,43 +118,7 @@ function initMap() {
L.control.locate({ showPopup: false }).addTo(MAP); L.control.locate({ showPopup: false }).addTo(MAP);
} }
function initCities() { function initPins() {
const select = document.getElementById('city-select');
while (select.options.length > 1) {
select.options.remove(1);
}
for (const city of Object.values(CITIES)) {
const opt = document.createElement('option');
opt.value = city.id;
opt.innerText = city.name;
select.add(opt);
}
select.hidden = false;
}
// ---------------------
// Interactive
// ---------------------
function showCityOverview() {
LAYER.clearLayers();
MAP.setView(DEFAULT_CENTER, DEFAULT_ZOOM);
setCity(null);
PLACES = {};
updateCounter();
for (const city of Object.values(CITIES)) {
makeCityMarker(city).addTo(LAYER);
}
}
async function showCity(cityId) {
const city = CITIES[cityId];
LAYER.clearLayers();
MAP.setView(city.loc, city.zoom);
setCity(city);
await loadCity(cityId);
var bounds = L.latLngBounds(); var bounds = L.latLngBounds();
for (const place of Object.values(PLACES)) { for (const place of Object.values(PLACES)) {
const marker = makeMarker(place).addTo(LAYER); const marker = makeMarker(place).addTo(LAYER);
@@ -203,23 +132,14 @@ async function showCity(cityId) {
async function start() { async function start() {
initMap(); initMap();
await loadCities(); await loadData();
initCities(); initPins();
// LAYER.clearLayers();
// MAP.setView(city.loc, city.zoom);
const [city_slug, place_id] = location.hash.substring(1).split('|'); const place_id = location.hash.substring(1);
const city_id = city_slug ? getCityId(city_slug) : null;
if (city_id) {
await showCity(city_id);
if (place_id) { if (place_id) {
setPlace(place_id); setPlace(place_id);
} }
} else {
const available_cities = Object.keys(CITIES);
if (available_cities.length === 1) {
await showCity(available_cities[0]);
} else {
showCityOverview();
}
}
document.getElementById('loading').hidden = true; document.getElementById('loading').hidden = true;
} }

View File

@@ -32,7 +32,6 @@ html, body {
color: #666; color: #666;
padding: 4px 6px 2px; padding: 4px 6px 2px;
border-radius: 8px; border-radius: 8px;
font-size: smaller;
} }
.pin svg { .pin svg {
@@ -96,9 +95,6 @@ html, body {
} }
} }
.pin-city {
fill-opacity: 0;
}
.fc0 { .fc0 {
fill: #FFF; fill: #FFF;
} }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 155 KiB

After

Width:  |  Height:  |  Size: 141 KiB