Files
labhelper/boxes/views.py
2025-12-28 23:22:13 +01:00

89 lines
2.6 KiB
Python

from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from .forms import ThingFormSet
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})
def add_things(request, box_id):
"""Add multiple things to a box at once."""
box = get_object_or_404(Box, pk=box_id)
success_message = None
if request.method == 'POST':
formset = ThingFormSet(request.POST)
if formset.is_valid():
things = formset.save(commit=False)
created_count = 0
for thing in things:
if thing.name or thing.thing_type or thing.description or thing.picture:
thing.box = box
thing.save()
created_count += 1
if created_count > 0:
success_message = f'Added {created_count} thing{"s" if created_count > 1 else ""} successfully.'
formset = ThingFormSet()
else:
formset = ThingFormSet()
return render(request, 'boxes/add_things.html', {
'box': box,
'formset': formset,
'success_message': success_message,
})