Files
labhelper/boxes/views.py
Adrian A. Baumann f30627196e
All checks were successful
Build containers when image tags change / build-if-image-changed (., web, containers, main container, git.baumann.gr/adebaumann/labhelper) (push) Successful in 32s
Build containers when image tags change / build-if-image-changed (data-loader, loader, initContainers, init-container, git.baumann.gr/adebaumann/labhelper-data-loader) (push) Successful in 7s
Add search page and thing detail with AJAX
2025-12-28 22:39:57 +01:00

58 lines
1.6 KiB
Python

from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, render
from .models import Box, Thing
def index(request):
"""Simple index page."""
html = '<h1>LabHelper</h1><p><a href="/search/">Search Things</a> | <a href="/admin/">Admin</a></p>'
return HttpResponse(html)
def box_detail(request, box_id):
"""Display contents of a box."""
box = get_object_or_404(Box, pk=box_id)
things = box.things.select_related('thing_type').all()
return render(request, 'boxes/box_detail.html', {
'box': box,
'things': things,
})
def thing_detail(request, thing_id):
"""Display details of a thing."""
thing = get_object_or_404(
Thing.objects.select_related('thing_type', 'box', 'box__box_type'),
pk=thing_id
)
return render(request, 'boxes/thing_detail.html', {'thing': thing})
def search(request):
"""Search page for things."""
return render(request, 'boxes/search.html')
def search_api(request):
"""AJAX endpoint for searching things."""
query = request.GET.get('q', '').strip()
if len(query) < 2:
return JsonResponse({'results': []})
things = Thing.objects.filter(
name__icontains=query
).select_related('thing_type', 'box')[:50]
results = [
{
'id': thing.id,
'name': thing.name,
'type': thing.thing_type.name,
'box': thing.box.id,
'description': thing.description[:100] if thing.description else '',
}
for thing in things
]
return JsonResponse({'results': results})