Add BackgroundImage model and enhance card templates with dynamic backgrounds

This commit is contained in:
Ross
2025-12-04 22:16:33 +00:00
parent 33fbae9426
commit d299f7ffd3
12 changed files with 253 additions and 16 deletions
+11 -7
View File
@@ -1,7 +1,7 @@
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseBadRequest
from django.template.loader import render_to_string
from .models import Dinosaur
from .models import Dinosaur, BackgroundImage
from .forms import DinosaurForm
@@ -11,18 +11,21 @@ def is_htmx(request):
def card_list(request):
cards = Dinosaur.objects.all()
background = BackgroundImage.get_active() if BackgroundImage.objects.exists() else None
if is_htmx(request):
return render(request, 'cards/_cards_list.html', {'cards': cards})
return render(request, 'cards/list.html', {'cards': cards})
return render(request, 'cards/_cards_list.html', {'cards': cards, 'background': background})
return render(request, 'cards/list.html', {'cards': cards, 'background': background})
def card_create(request):
background = BackgroundImage.get_active() if BackgroundImage.objects.exists() else None
if request.method == 'POST':
form = DinosaurForm(request.POST, request.FILES)
if form.is_valid():
card = form.save()
if is_htmx(request):
card_html = render_to_string('cards/_card_item.html', {'card': card}, request=request)
card_html = render_to_string('cards/_card_item.html', {'card': card, 'background': background}, request=request)
# Also return an out-of-band fragment to replace/clear the form container
form_html = render_to_string('cards/_form.html', {'form': DinosaurForm()}, request=request)
oob = f'<div id="htmx-form" hx-swap-oob="true">{form_html}</div>'
@@ -37,17 +40,18 @@ def card_create(request):
else:
form = DinosaurForm()
return render(request, 'cards/_form.html', {'form': form})
return render(request, 'cards/_form.html', {'form': form, 'background': background})
def card_edit(request, pk):
card = get_object_or_404(Dinosaur, pk=pk)
background = BackgroundImage.get_active() if BackgroundImage.objects.exists() else None
if request.method == 'POST':
form = DinosaurForm(request.POST, request.FILES, instance=card)
if form.is_valid():
card = form.save()
if is_htmx(request):
card_html = render_to_string('cards/_card_item.html', {'card': card}, request=request)
card_html = render_to_string('cards/_card_item.html', {'card': card, 'background': background}, request=request)
# Clear the form container via OOB so the edit form disappears after successful save
oob = '<div id="htmx-form" hx-swap-oob="true"></div>'
return HttpResponse(card_html + oob)
@@ -60,7 +64,7 @@ def card_edit(request, pk):
else:
form = DinosaurForm(instance=card)
return render(request, 'cards/_form.html', {'form': form, 'card': card})
return render(request, 'cards/_form.html', {'form': form, 'card': card, 'background': background})
def card_delete(request, pk):