mirror of
https://github.com/pacnpal/thrillwiki_django_no_react.git
synced 2025-12-20 17:51:08 -05:00
Add autocomplete functionality for parks: implement URLs, views, and templates for real-time suggestions
This commit is contained in:
52
autocomplete/views.py
Normal file
52
autocomplete/views.py
Normal file
@@ -0,0 +1,52 @@
|
||||
from django.http import JsonResponse, HttpResponse
|
||||
from django.shortcuts import get_object_or_404, render
|
||||
from django.apps import apps
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
|
||||
def items(request, ac_name):
|
||||
"""Return autocomplete items for a given autocomplete class."""
|
||||
try:
|
||||
# Get the autocomplete class from the registry
|
||||
ac_class = apps.get_app_config('autocomplete').get_autocomplete_class(ac_name)
|
||||
if not ac_class:
|
||||
raise ImproperlyConfigured(f"No autocomplete class found for {ac_name}")
|
||||
|
||||
# Create instance and get results
|
||||
ac = ac_class()
|
||||
search = request.GET.get('search', '')
|
||||
|
||||
# Check minimum search length
|
||||
if len(search) < ac.minimum_search_length:
|
||||
return HttpResponse('')
|
||||
|
||||
# Get and format results
|
||||
results = ac.get_search_results(search)[:ac.max_results]
|
||||
formatted_results = [ac.format_result(obj) for obj in results]
|
||||
|
||||
# Render suggestions template
|
||||
return render(request, 'autocomplete/suggestions.html', {
|
||||
'results': formatted_results
|
||||
})
|
||||
except Exception as e:
|
||||
return HttpResponse(str(e), status=400)
|
||||
|
||||
def toggle(request, ac_name):
|
||||
"""Toggle selection state for an autocomplete item."""
|
||||
try:
|
||||
# Get the autocomplete class from the registry
|
||||
ac_class = apps.get_app_config('autocomplete').get_autocomplete_class(ac_name)
|
||||
if not ac_class:
|
||||
raise ImproperlyConfigured(f"No autocomplete class found for {ac_name}")
|
||||
|
||||
# Create instance and handle toggle
|
||||
ac = ac_class()
|
||||
item_id = request.POST.get('id')
|
||||
if not item_id:
|
||||
raise ValueError("No item ID provided")
|
||||
|
||||
# Get the object and format it
|
||||
obj = get_object_or_404(ac.model, pk=item_id)
|
||||
result = ac.format_result(obj)
|
||||
return JsonResponse(result)
|
||||
except Exception as e:
|
||||
return JsonResponse({'error': str(e)}, status=400)
|
||||
Reference in New Issue
Block a user