Files
labhelper/boxes/views.py
Adrian A. Baumann f6a953158d
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 8s
Add form to add multiple things to a box
2025-12-28 22:50:37 +01:00

90 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)
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
print(f'DEBUG: created_count={created_count}')
if created_count > 0:
print(f'DEBUG: Redirecting to box_detail with box_id={box_id}')
return redirect('box_detail', box_id=box_id)
else:
print('DEBUG: No valid data submitted')
else:
formset = ThingFormSet()
return render(request, 'boxes/add_things.html', {
'box': box,
'formset': formset,
})