mirror of
https://github.com/pacnpal/thrillwiki_django_no_react.git
synced 2025-12-20 08:51:09 -05:00
okay fine
This commit is contained in:
31
location/admin.py
Normal file
31
location/admin.py
Normal file
@@ -0,0 +1,31 @@
|
||||
from django.contrib import admin
|
||||
from django.contrib.contenttypes.admin import GenericTabularInline
|
||||
from .models import Location
|
||||
|
||||
@admin.register(Location)
|
||||
class LocationAdmin(admin.ModelAdmin):
|
||||
list_display = ('name', 'location_type', 'city', 'state', 'country')
|
||||
list_filter = ('location_type', 'country', 'state', 'city')
|
||||
search_fields = ('name', 'street_address', 'city', 'state', 'country')
|
||||
readonly_fields = ('created_at', 'updated_at')
|
||||
fieldsets = (
|
||||
('Basic Information', {
|
||||
'fields': ('name', 'location_type')
|
||||
}),
|
||||
('Geographic Coordinates', {
|
||||
'fields': ('latitude', 'longitude')
|
||||
}),
|
||||
('Address', {
|
||||
'fields': ('street_address', 'city', 'state', 'country', 'postal_code')
|
||||
}),
|
||||
('Content Type', {
|
||||
'fields': ('content_type', 'object_id')
|
||||
}),
|
||||
('Metadata', {
|
||||
'fields': ('created_at', 'updated_at'),
|
||||
'classes': ('collapse',)
|
||||
})
|
||||
)
|
||||
|
||||
def get_queryset(self, request):
|
||||
return super().get_queryset(request).select_related('content_type')
|
||||
5
location/apps.py
Normal file
5
location/apps.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
class LocationConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'location'
|
||||
79
location/forms.py
Normal file
79
location/forms.py
Normal file
@@ -0,0 +1,79 @@
|
||||
from django import forms
|
||||
from .models import Location
|
||||
|
||||
class LocationForm(forms.ModelForm):
|
||||
"""Form for creating and updating Location objects"""
|
||||
|
||||
class Meta:
|
||||
model = Location
|
||||
fields = [
|
||||
'name',
|
||||
'location_type',
|
||||
'latitude',
|
||||
'longitude',
|
||||
'street_address',
|
||||
'city',
|
||||
'state',
|
||||
'country',
|
||||
'postal_code',
|
||||
]
|
||||
widgets = {
|
||||
'latitude': forms.NumberInput(attrs={
|
||||
'step': 'any',
|
||||
'class': 'location-lat',
|
||||
'data-map-target': 'lat'
|
||||
}),
|
||||
'longitude': forms.NumberInput(attrs={
|
||||
'step': 'any',
|
||||
'class': 'location-lng',
|
||||
'data-map-target': 'lng'
|
||||
})
|
||||
}
|
||||
|
||||
class LocationSearchForm(forms.Form):
|
||||
"""Form for searching locations using OpenStreetMap Nominatim"""
|
||||
|
||||
query = forms.CharField(
|
||||
max_length=255,
|
||||
required=True,
|
||||
widget=forms.TextInput(attrs={
|
||||
'placeholder': 'Search for a location...',
|
||||
'class': 'location-search',
|
||||
'data-action': 'search#query',
|
||||
'autocomplete': 'off'
|
||||
})
|
||||
)
|
||||
|
||||
# Hidden fields for storing selected location data
|
||||
selected_lat = forms.DecimalField(
|
||||
required=False,
|
||||
widget=forms.HiddenInput(attrs={'data-search-target': 'selectedLat'})
|
||||
)
|
||||
selected_lng = forms.DecimalField(
|
||||
required=False,
|
||||
widget=forms.HiddenInput(attrs={'data-search-target': 'selectedLng'})
|
||||
)
|
||||
selected_name = forms.CharField(
|
||||
required=False,
|
||||
widget=forms.HiddenInput(attrs={'data-search-target': 'selectedName'})
|
||||
)
|
||||
selected_address = forms.CharField(
|
||||
required=False,
|
||||
widget=forms.HiddenInput(attrs={'data-search-target': 'selectedAddress'})
|
||||
)
|
||||
selected_city = forms.CharField(
|
||||
required=False,
|
||||
widget=forms.HiddenInput(attrs={'data-search-target': 'selectedCity'})
|
||||
)
|
||||
selected_state = forms.CharField(
|
||||
required=False,
|
||||
widget=forms.HiddenInput(attrs={'data-search-target': 'selectedState'})
|
||||
)
|
||||
selected_country = forms.CharField(
|
||||
required=False,
|
||||
widget=forms.HiddenInput(attrs={'data-search-target': 'selectedCountry'})
|
||||
)
|
||||
selected_postal_code = forms.CharField(
|
||||
required=False,
|
||||
widget=forms.HiddenInput(attrs={'data-search-target': 'selectedPostalCode'})
|
||||
)
|
||||
208
location/migrations/0001_initial.py
Normal file
208
location/migrations/0001_initial.py
Normal file
@@ -0,0 +1,208 @@
|
||||
# Generated by Django 5.1.2 on 2024-11-02 23:28
|
||||
|
||||
import django.core.validators
|
||||
import django.db.models.deletion
|
||||
import simple_history.models
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
("contenttypes", "0002_remove_content_type_name"),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="HistoricalLocation",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigIntegerField(
|
||||
auto_created=True, blank=True, db_index=True, verbose_name="ID"
|
||||
),
|
||||
),
|
||||
("object_id", models.PositiveIntegerField()),
|
||||
(
|
||||
"name",
|
||||
models.CharField(
|
||||
help_text="Name of the location (e.g. business name, landmark)",
|
||||
max_length=255,
|
||||
),
|
||||
),
|
||||
(
|
||||
"location_type",
|
||||
models.CharField(
|
||||
help_text="Type of location (e.g. business, landmark, address)",
|
||||
max_length=50,
|
||||
),
|
||||
),
|
||||
(
|
||||
"latitude",
|
||||
models.DecimalField(
|
||||
decimal_places=6,
|
||||
help_text="Latitude coordinate",
|
||||
max_digits=9,
|
||||
validators=[
|
||||
django.core.validators.MinValueValidator(-90),
|
||||
django.core.validators.MaxValueValidator(90),
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"longitude",
|
||||
models.DecimalField(
|
||||
decimal_places=6,
|
||||
help_text="Longitude coordinate",
|
||||
max_digits=9,
|
||||
validators=[
|
||||
django.core.validators.MinValueValidator(-180),
|
||||
django.core.validators.MaxValueValidator(180),
|
||||
],
|
||||
),
|
||||
),
|
||||
("street_address", models.CharField(blank=True, max_length=255)),
|
||||
("city", models.CharField(max_length=100)),
|
||||
(
|
||||
"state",
|
||||
models.CharField(
|
||||
blank=True, help_text="State/Region/Province", max_length=100
|
||||
),
|
||||
),
|
||||
("country", models.CharField(max_length=100)),
|
||||
("postal_code", models.CharField(blank=True, max_length=20)),
|
||||
("created_at", models.DateTimeField(blank=True, editable=False)),
|
||||
("updated_at", models.DateTimeField(blank=True, editable=False)),
|
||||
("history_id", models.AutoField(primary_key=True, serialize=False)),
|
||||
("history_date", models.DateTimeField(db_index=True)),
|
||||
("history_change_reason", models.CharField(max_length=100, null=True)),
|
||||
(
|
||||
"history_type",
|
||||
models.CharField(
|
||||
choices=[("+", "Created"), ("~", "Changed"), ("-", "Deleted")],
|
||||
max_length=1,
|
||||
),
|
||||
),
|
||||
(
|
||||
"content_type",
|
||||
models.ForeignKey(
|
||||
blank=True,
|
||||
db_constraint=False,
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.DO_NOTHING,
|
||||
related_name="+",
|
||||
to="contenttypes.contenttype",
|
||||
),
|
||||
),
|
||||
(
|
||||
"history_user",
|
||||
models.ForeignKey(
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
related_name="+",
|
||||
to=settings.AUTH_USER_MODEL,
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"verbose_name": "historical location",
|
||||
"verbose_name_plural": "historical locations",
|
||||
"ordering": ("-history_date", "-history_id"),
|
||||
"get_latest_by": ("history_date", "history_id"),
|
||||
},
|
||||
bases=(simple_history.models.HistoricalChanges, models.Model),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="Location",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
("object_id", models.PositiveIntegerField()),
|
||||
(
|
||||
"name",
|
||||
models.CharField(
|
||||
help_text="Name of the location (e.g. business name, landmark)",
|
||||
max_length=255,
|
||||
),
|
||||
),
|
||||
(
|
||||
"location_type",
|
||||
models.CharField(
|
||||
help_text="Type of location (e.g. business, landmark, address)",
|
||||
max_length=50,
|
||||
),
|
||||
),
|
||||
(
|
||||
"latitude",
|
||||
models.DecimalField(
|
||||
decimal_places=6,
|
||||
help_text="Latitude coordinate",
|
||||
max_digits=9,
|
||||
validators=[
|
||||
django.core.validators.MinValueValidator(-90),
|
||||
django.core.validators.MaxValueValidator(90),
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"longitude",
|
||||
models.DecimalField(
|
||||
decimal_places=6,
|
||||
help_text="Longitude coordinate",
|
||||
max_digits=9,
|
||||
validators=[
|
||||
django.core.validators.MinValueValidator(-180),
|
||||
django.core.validators.MaxValueValidator(180),
|
||||
],
|
||||
),
|
||||
),
|
||||
("street_address", models.CharField(blank=True, max_length=255)),
|
||||
("city", models.CharField(max_length=100)),
|
||||
(
|
||||
"state",
|
||||
models.CharField(
|
||||
blank=True, help_text="State/Region/Province", max_length=100
|
||||
),
|
||||
),
|
||||
("country", models.CharField(max_length=100)),
|
||||
("postal_code", models.CharField(blank=True, max_length=20)),
|
||||
("created_at", models.DateTimeField(auto_now_add=True)),
|
||||
("updated_at", models.DateTimeField(auto_now=True)),
|
||||
(
|
||||
"content_type",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
to="contenttypes.contenttype",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"ordering": ["name"],
|
||||
"indexes": [
|
||||
models.Index(
|
||||
fields=["content_type", "object_id"],
|
||||
name="location_lo_content_9ee1bd_idx",
|
||||
),
|
||||
models.Index(
|
||||
fields=["latitude", "longitude"],
|
||||
name="location_lo_latitud_7045c4_idx",
|
||||
),
|
||||
models.Index(fields=["city"], name="location_lo_city_99f908_idx"),
|
||||
models.Index(
|
||||
fields=["country"], name="location_lo_country_b75eba_idx"
|
||||
),
|
||||
],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,84 @@
|
||||
# Generated by Django 5.1.2 on 2024-11-02 23:34
|
||||
|
||||
import django.core.validators
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("location", "0001_initial"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name="historicallocation",
|
||||
name="city",
|
||||
field=models.CharField(blank=True, max_length=100),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="historicallocation",
|
||||
name="latitude",
|
||||
field=models.DecimalField(
|
||||
blank=True,
|
||||
decimal_places=6,
|
||||
help_text="Latitude coordinate",
|
||||
max_digits=9,
|
||||
null=True,
|
||||
validators=[
|
||||
django.core.validators.MinValueValidator(-90),
|
||||
django.core.validators.MaxValueValidator(90),
|
||||
],
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="historicallocation",
|
||||
name="longitude",
|
||||
field=models.DecimalField(
|
||||
blank=True,
|
||||
decimal_places=6,
|
||||
help_text="Longitude coordinate",
|
||||
max_digits=9,
|
||||
null=True,
|
||||
validators=[
|
||||
django.core.validators.MinValueValidator(-180),
|
||||
django.core.validators.MaxValueValidator(180),
|
||||
],
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="location",
|
||||
name="city",
|
||||
field=models.CharField(blank=True, max_length=100),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="location",
|
||||
name="latitude",
|
||||
field=models.DecimalField(
|
||||
blank=True,
|
||||
decimal_places=6,
|
||||
help_text="Latitude coordinate",
|
||||
max_digits=9,
|
||||
null=True,
|
||||
validators=[
|
||||
django.core.validators.MinValueValidator(-90),
|
||||
django.core.validators.MaxValueValidator(90),
|
||||
],
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="location",
|
||||
name="longitude",
|
||||
field=models.DecimalField(
|
||||
blank=True,
|
||||
decimal_places=6,
|
||||
help_text="Longitude coordinate",
|
||||
max_digits=9,
|
||||
null=True,
|
||||
validators=[
|
||||
django.core.validators.MinValueValidator(-180),
|
||||
django.core.validators.MaxValueValidator(180),
|
||||
],
|
||||
),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,67 @@
|
||||
# Generated by Django 5.1.2 on 2024-11-02 23:35
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("location", "0002_alter_historicallocation_city_and_more"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name="historicallocation",
|
||||
name="city",
|
||||
field=models.CharField(blank=True, max_length=100, null=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="historicallocation",
|
||||
name="country",
|
||||
field=models.CharField(blank=True, max_length=100, null=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="historicallocation",
|
||||
name="postal_code",
|
||||
field=models.CharField(blank=True, max_length=20, null=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="historicallocation",
|
||||
name="state",
|
||||
field=models.CharField(
|
||||
blank=True, help_text="State/Region/Province", max_length=100, null=True
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="historicallocation",
|
||||
name="street_address",
|
||||
field=models.CharField(blank=True, max_length=255, null=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="location",
|
||||
name="city",
|
||||
field=models.CharField(blank=True, max_length=100, null=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="location",
|
||||
name="country",
|
||||
field=models.CharField(blank=True, max_length=100, null=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="location",
|
||||
name="postal_code",
|
||||
field=models.CharField(blank=True, max_length=20, null=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="location",
|
||||
name="state",
|
||||
field=models.CharField(
|
||||
blank=True, help_text="State/Region/Province", max_length=100, null=True
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="location",
|
||||
name="street_address",
|
||||
field=models.CharField(blank=True, max_length=255, null=True),
|
||||
),
|
||||
]
|
||||
0
location/migrations/__init__.py
Normal file
0
location/migrations/__init__.py
Normal file
96
location/models.py
Normal file
96
location/models.py
Normal file
@@ -0,0 +1,96 @@
|
||||
from django.db import models
|
||||
from django.contrib.contenttypes.fields import GenericForeignKey
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.core.validators import MinValueValidator, MaxValueValidator
|
||||
from simple_history.models import HistoricalRecords
|
||||
|
||||
class Location(models.Model):
|
||||
"""
|
||||
A generic location model that can be associated with any model
|
||||
using GenericForeignKey. Stores detailed location information
|
||||
including coordinates and address components.
|
||||
"""
|
||||
# Generic relation fields
|
||||
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
|
||||
object_id = models.PositiveIntegerField()
|
||||
content_object = GenericForeignKey('content_type', 'object_id')
|
||||
|
||||
# Location name and type
|
||||
name = models.CharField(max_length=255, help_text="Name of the location (e.g. business name, landmark)")
|
||||
location_type = models.CharField(max_length=50, help_text="Type of location (e.g. business, landmark, address)")
|
||||
|
||||
# Geographic coordinates
|
||||
latitude = models.DecimalField(
|
||||
max_digits=9,
|
||||
decimal_places=6,
|
||||
validators=[
|
||||
MinValueValidator(-90),
|
||||
MaxValueValidator(90)
|
||||
],
|
||||
help_text="Latitude coordinate",
|
||||
null=True,
|
||||
blank=True
|
||||
)
|
||||
longitude = models.DecimalField(
|
||||
max_digits=9,
|
||||
decimal_places=6,
|
||||
validators=[
|
||||
MinValueValidator(-180),
|
||||
MaxValueValidator(180)
|
||||
],
|
||||
help_text="Longitude coordinate",
|
||||
null=True,
|
||||
blank=True
|
||||
)
|
||||
|
||||
# Address components - all made nullable
|
||||
street_address = models.CharField(max_length=255, blank=True, null=True)
|
||||
city = models.CharField(max_length=100, blank=True, null=True)
|
||||
state = models.CharField(max_length=100, blank=True, null=True, help_text="State/Region/Province")
|
||||
country = models.CharField(max_length=100, blank=True, null=True)
|
||||
postal_code = models.CharField(max_length=20, blank=True, null=True)
|
||||
|
||||
# Metadata
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
history = HistoricalRecords()
|
||||
|
||||
class Meta:
|
||||
indexes = [
|
||||
models.Index(fields=['content_type', 'object_id']),
|
||||
models.Index(fields=['latitude', 'longitude']),
|
||||
models.Index(fields=['city']),
|
||||
models.Index(fields=['country']),
|
||||
]
|
||||
ordering = ['name']
|
||||
|
||||
def __str__(self):
|
||||
location_parts = []
|
||||
if self.city:
|
||||
location_parts.append(self.city)
|
||||
if self.country:
|
||||
location_parts.append(self.country)
|
||||
location_str = ", ".join(location_parts) if location_parts else "Unknown location"
|
||||
return f"{self.name} ({location_str})"
|
||||
|
||||
def get_formatted_address(self):
|
||||
"""Returns a formatted address string"""
|
||||
components = []
|
||||
if self.street_address:
|
||||
components.append(self.street_address)
|
||||
if self.city:
|
||||
components.append(self.city)
|
||||
if self.state:
|
||||
components.append(self.state)
|
||||
if self.postal_code:
|
||||
components.append(self.postal_code)
|
||||
if self.country:
|
||||
components.append(self.country)
|
||||
return ", ".join(components) if components else ""
|
||||
|
||||
@property
|
||||
def coordinates(self):
|
||||
"""Returns coordinates as a tuple"""
|
||||
if self.latitude is not None and self.longitude is not None:
|
||||
return (float(self.latitude), float(self.longitude))
|
||||
return None
|
||||
12
location/urls.py
Normal file
12
location/urls.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from django.urls import path
|
||||
from . import views
|
||||
|
||||
app_name = 'location'
|
||||
|
||||
urlpatterns = [
|
||||
path('search/', views.LocationSearchView.as_view(), name='search'),
|
||||
path('reverse-geocode/', views.reverse_geocode, name='reverse_geocode'),
|
||||
path('create/', views.LocationCreateView.as_view(), name='create'),
|
||||
path('<int:pk>/update/', views.LocationUpdateView.as_view(), name='update'),
|
||||
path('<int:pk>/delete/', views.LocationDeleteView.as_view(), name='delete'),
|
||||
]
|
||||
200
location/views.py
Normal file
200
location/views.py
Normal file
@@ -0,0 +1,200 @@
|
||||
import json
|
||||
import requests
|
||||
from django.views.generic import View
|
||||
from django.http import JsonResponse
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.core.cache import cache
|
||||
from django.conf import settings
|
||||
from django.views.decorators.http import require_http_methods
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views.decorators.csrf import csrf_protect
|
||||
from django.db.models import Q
|
||||
from .models import Location
|
||||
|
||||
class LocationSearchView(View):
|
||||
"""
|
||||
View for searching locations using OpenStreetMap Nominatim.
|
||||
Returns search results in JSON format.
|
||||
"""
|
||||
|
||||
@method_decorator(csrf_protect)
|
||||
def get(self, request, *args, **kwargs):
|
||||
query = request.GET.get('q', '').strip()
|
||||
filter_type = request.GET.get('type', '') # country, state, city
|
||||
filter_parks = request.GET.get('filter_parks', 'false') == 'true'
|
||||
|
||||
if not query:
|
||||
return JsonResponse({'results': []})
|
||||
|
||||
# Check cache first
|
||||
cache_key = f'location_search_{query}_{filter_type}_{filter_parks}'
|
||||
cached_results = cache.get(cache_key)
|
||||
if cached_results:
|
||||
return JsonResponse({'results': cached_results})
|
||||
|
||||
# Search OpenStreetMap
|
||||
try:
|
||||
params = {
|
||||
'q': query,
|
||||
'format': 'json',
|
||||
'addressdetails': 1,
|
||||
'limit': 10
|
||||
}
|
||||
|
||||
# Add type-specific filters
|
||||
if filter_type == 'country':
|
||||
params['featuretype'] = 'country'
|
||||
elif filter_type == 'state':
|
||||
params['featuretype'] = 'state'
|
||||
elif filter_type == 'city':
|
||||
params['featuretype'] = 'city'
|
||||
|
||||
response = requests.get(
|
||||
'https://nominatim.openstreetmap.org/search',
|
||||
params=params,
|
||||
headers={'User-Agent': 'ThrillWiki/1.0'}
|
||||
)
|
||||
response.raise_for_status()
|
||||
results = response.json()
|
||||
except requests.RequestException as e:
|
||||
return JsonResponse({
|
||||
'error': 'Failed to fetch location data',
|
||||
'details': str(e)
|
||||
}, status=500)
|
||||
|
||||
# Process and format results
|
||||
formatted_results = []
|
||||
for result in results:
|
||||
address = result.get('address', {})
|
||||
formatted_result = {
|
||||
'name': result.get('display_name', ''),
|
||||
'lat': result.get('lat'),
|
||||
'lon': result.get('lon'),
|
||||
'type': result.get('type', ''),
|
||||
'address': {
|
||||
'street': address.get('road', ''),
|
||||
'house_number': address.get('house_number', ''),
|
||||
'city': address.get('city', '') or address.get('town', '') or address.get('village', ''),
|
||||
'state': address.get('state', ''),
|
||||
'country': address.get('country', ''),
|
||||
'postcode': address.get('postcode', '')
|
||||
}
|
||||
}
|
||||
|
||||
# If filtering by parks, only include results that have parks
|
||||
if filter_parks:
|
||||
location_exists = Location.objects.filter(
|
||||
Q(country__icontains=formatted_result['address']['country']) &
|
||||
(Q(state__icontains=formatted_result['address']['state']) if formatted_result['address']['state'] else Q()) &
|
||||
(Q(city__icontains=formatted_result['address']['city']) if formatted_result['address']['city'] else Q())
|
||||
).exists()
|
||||
if not location_exists:
|
||||
continue
|
||||
|
||||
formatted_results.append(formatted_result)
|
||||
|
||||
# Cache results for 1 hour
|
||||
cache.set(cache_key, formatted_results, 3600)
|
||||
|
||||
return JsonResponse({'results': formatted_results})
|
||||
|
||||
class LocationCreateView(LoginRequiredMixin, View):
|
||||
"""View for creating new Location objects"""
|
||||
|
||||
@method_decorator(csrf_protect)
|
||||
def post(self, request, *args, **kwargs):
|
||||
form = LocationForm(request.POST)
|
||||
if form.is_valid():
|
||||
location = form.save()
|
||||
return JsonResponse({
|
||||
'id': location.id,
|
||||
'name': location.name,
|
||||
'formatted_address': location.get_formatted_address(),
|
||||
'coordinates': location.coordinates
|
||||
})
|
||||
return JsonResponse({'errors': form.errors}, status=400)
|
||||
|
||||
class LocationUpdateView(LoginRequiredMixin, View):
|
||||
"""View for updating existing Location objects"""
|
||||
|
||||
@method_decorator(csrf_protect)
|
||||
def post(self, request, *args, **kwargs):
|
||||
location = Location.objects.get(pk=kwargs['pk'])
|
||||
form = LocationForm(request.POST, instance=location)
|
||||
if form.is_valid():
|
||||
location = form.save()
|
||||
return JsonResponse({
|
||||
'id': location.id,
|
||||
'name': location.name,
|
||||
'formatted_address': location.get_formatted_address(),
|
||||
'coordinates': location.coordinates
|
||||
})
|
||||
return JsonResponse({'errors': form.errors}, status=400)
|
||||
|
||||
class LocationDeleteView(LoginRequiredMixin, View):
|
||||
"""View for deleting Location objects"""
|
||||
|
||||
@method_decorator(csrf_protect)
|
||||
def post(self, request, *args, **kwargs):
|
||||
try:
|
||||
location = Location.objects.get(pk=kwargs['pk'])
|
||||
location.delete()
|
||||
return JsonResponse({'status': 'success'})
|
||||
except Location.DoesNotExist:
|
||||
return JsonResponse({'error': 'Location not found'}, status=404)
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
def reverse_geocode(request):
|
||||
"""
|
||||
View for reverse geocoding coordinates to address using OpenStreetMap.
|
||||
Returns address details in JSON format.
|
||||
"""
|
||||
lat = request.GET.get('lat')
|
||||
lon = request.GET.get('lon')
|
||||
|
||||
if not lat or not lon:
|
||||
return JsonResponse({'error': 'Latitude and longitude are required'}, status=400)
|
||||
|
||||
# Check cache first
|
||||
cache_key = f'reverse_geocode_{lat}_{lon}'
|
||||
cached_result = cache.get(cache_key)
|
||||
if cached_result:
|
||||
return JsonResponse(cached_result)
|
||||
|
||||
try:
|
||||
response = requests.get(
|
||||
'https://nominatim.openstreetmap.org/reverse',
|
||||
params={
|
||||
'lat': lat,
|
||||
'lon': lon,
|
||||
'format': 'json',
|
||||
'addressdetails': 1
|
||||
},
|
||||
headers={'User-Agent': 'ThrillWiki/1.0'}
|
||||
)
|
||||
response.raise_for_status()
|
||||
result = response.json()
|
||||
|
||||
address = result.get('address', {})
|
||||
formatted_result = {
|
||||
'name': result.get('display_name', ''),
|
||||
'address': {
|
||||
'street': address.get('road', ''),
|
||||
'house_number': address.get('house_number', ''),
|
||||
'city': address.get('city', '') or address.get('town', '') or address.get('village', ''),
|
||||
'state': address.get('state', ''),
|
||||
'country': address.get('country', ''),
|
||||
'postcode': address.get('postcode', '')
|
||||
}
|
||||
}
|
||||
|
||||
# Cache result for 1 day
|
||||
cache.set(cache_key, formatted_result, 86400)
|
||||
|
||||
return JsonResponse(formatted_result)
|
||||
|
||||
except requests.RequestException as e:
|
||||
return JsonResponse({
|
||||
'error': 'Failed to fetch address data',
|
||||
'details': str(e)
|
||||
}, status=500)
|
||||
Reference in New Issue
Block a user