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 = '
LabHelper
Search Things | Admin
'
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})