This commit is contained in:
Ross
2025-12-04 21:01:45 +00:00
commit 75398cf53f
28 changed files with 599 additions and 0 deletions
View File
+1
View File
@@ -0,0 +1 @@
# cards app
+8
View File
@@ -0,0 +1,8 @@
from django.contrib import admin
from .models import Dinosaur
@admin.register(Dinosaur)
class DinosaurAdmin(admin.ModelAdmin):
list_display = ('name', 'era', 'diet', 'speed', 'weight', 'intelligence')
search_fields = ('name', 'era', 'diet')
+6
View File
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class CardsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'cards'
+14
View File
@@ -0,0 +1,14 @@
from django import forms
from .models import Dinosaur
class DinosaurForm(forms.ModelForm):
class Meta:
model = Dinosaur
fields = [
'name', 'era', 'diet', 'description', 'image',
'speed', 'weight', 'intelligence', 'height',
]
widgets = {
'description': forms.Textarea(attrs={'rows': 3}),
}
+33
View File
@@ -0,0 +1,33 @@
# Generated by Django 6.0 on 2025-12-04 20:55
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Dinosaur',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=120)),
('era', models.CharField(choices=[('triassic', 'Triassic'), ('jurassic', 'Jurassic'), ('cretaceous', 'Cretaceous')], default='jurassic', max_length=32)),
('diet', models.CharField(choices=[('herbivore', 'Herbivore'), ('carnivore', 'Carnivore'), ('omnivore', 'Omnivore')], default='herbivore', max_length=32)),
('description', models.TextField(blank=True)),
('image', models.ImageField(blank=True, null=True, upload_to='dinosaurs/')),
('speed', models.PositiveSmallIntegerField(default=50)),
('weight', models.PositiveSmallIntegerField(default=50)),
('intelligence', models.PositiveSmallIntegerField(default=50)),
('height', models.PositiveSmallIntegerField(default=50)),
('created_at', models.DateTimeField(auto_now_add=True)),
],
options={
'ordering': ['-created_at', 'name'],
},
),
]
+1
View File
@@ -0,0 +1 @@
# migrations package
+35
View File
@@ -0,0 +1,35 @@
from django.db import models
class Dinosaur(models.Model):
ERA_CHOICES = [
('triassic', 'Triassic'),
('jurassic', 'Jurassic'),
('cretaceous', 'Cretaceous'),
]
DIET_CHOICES = [
('herbivore', 'Herbivore'),
('carnivore', 'Carnivore'),
('omnivore', 'Omnivore'),
]
name = models.CharField(max_length=120)
era = models.CharField(max_length=32, choices=ERA_CHOICES, default='jurassic')
diet = models.CharField(max_length=32, choices=DIET_CHOICES, default='herbivore')
description = models.TextField(blank=True)
image = models.ImageField(upload_to='dinosaurs/', blank=True, null=True)
# Top-trump style stats (0-100)
speed = models.PositiveSmallIntegerField(default=50)
weight = models.PositiveSmallIntegerField(default=50)
intelligence = models.PositiveSmallIntegerField(default=50)
height = models.PositiveSmallIntegerField(default=50)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created_at', 'name']
def __str__(self):
return self.name
+15
View File
@@ -0,0 +1,15 @@
<div class="card" id="card-{{ card.pk }}">
<h3>{{ card.name }}</h3>
<div><strong>Era:</strong> {{ card.get_era_display }} — <strong>Diet:</strong> {{ card.get_diet_display }}</div>
<div>{{ card.description|linebreaksbr }}</div>
<ul>
<li>Speed: {{ card.speed }}</li>
<li>Weight: {{ card.weight }}</li>
<li>Intelligence: {{ card.intelligence }}</li>
<li>Height: {{ card.height }}</li>
</ul>
<div>
<button hx-get="{% url 'cards:edit' card.pk %}" hx-target="#htmx-form" hx-swap="innerHTML">Edit</button>
<button hx-post="{% url 'cards:delete' card.pk %}" hx-confirm="Delete this card?" hx-swap="none">Delete</button>
</div>
</div>
+8
View File
@@ -0,0 +1,8 @@
{% load static %}
<div class="grid">
{% for card in cards %}
{% include 'cards/_card_item.html' with card=card %}
{% empty %}
<p>No dinosaurs yet — add one!</p>
{% endfor %}
</div>
+47
View File
@@ -0,0 +1,47 @@
<div class="card-form card">
{% if card %}
<form method="post" enctype="multipart/form-data" action="{% url 'cards:edit' card.pk %}" hx-post="{% url 'cards:edit' card.pk %}" hx-target="#card-{{ card.pk }}" hx-swap="outerHTML">
{% else %}
{# Create: insert the returned card into the grid, and let the view also send an OOB form fragment to replace the form container when needed #}
<form method="post" enctype="multipart/form-data" action="{% url 'cards:create' %}" hx-post="{% url 'cards:create' %}" hx-target="#cards-list .grid" hx-swap="afterbegin">
{% endif %}
{% csrf_token %}
{{ form.non_field_errors }}
<div class="row">
{{ form.name.label_tag }}<br>
{{ form.name }}
</div>
<div class="row">
{{ form.era.label_tag }}<br>
{{ form.era }}
</div>
<div class="row">
{{ form.diet.label_tag }}<br>
{{ form.diet }}
</div>
<div class="row">
{{ form.description.label_tag }}<br>
{{ form.description }}
</div>
<div class="row">
{{ form.image.label_tag }}<br>
{{ form.image }}
</div>
<div class="row">
{{ form.speed.label_tag }} {{ form.speed }}
</div>
<div class="row">
{{ form.weight.label_tag }} {{ form.weight }}
</div>
<div class="row">
{{ form.intelligence.label_tag }} {{ form.intelligence }}
</div>
<div class="row">
{{ form.height.label_tag }} {{ form.height }}
</div>
<div class="row">
<button type="submit">Save</button>
<button type="button" onclick="document.getElementById('htmx-form').innerHTML=''">Cancel</button>
</div>
</form>
</div>
+22
View File
@@ -0,0 +1,22 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>TopTrumps - Dinosaurs</title>
<script src="https://unpkg.com/htmx.org@1.9.5"></script>
<style>
body{font-family:system-ui,Segoe UI,Roboto,Arial;margin:20px}
.card{border:1px solid #ddd;padding:12px;margin:8px;border-radius:6px}
.controls{margin-bottom:12px}
.grid{display:flex;flex-wrap:wrap}
.grid .card{width:220px}
form .row{margin-bottom:8px}
</style>
</head>
<body>
<h1>TopTrumps — Dinosaurs</h1>
<div id="messages"></div>
{% block content %}{% endblock %}
</body>
</html>
+14
View File
@@ -0,0 +1,14 @@
{% extends 'cards/base.html' %}
{% block content %}
<div class="controls">
<button hx-get="{% url 'cards:create' %}" hx-target="#htmx-form" hx-swap="innerHTML">Add Dinosaur</button>
</div>
<div id="htmx-form"></div>
<div id="cards-list">
{% include 'cards/_cards_list.html' %}
</div>
{% endblock %}
+11
View File
@@ -0,0 +1,11 @@
from django.urls import path
from . import views
app_name = 'cards'
urlpatterns = [
path('', views.card_list, name='list'),
path('create/', views.card_create, name='create'),
path('<int:pk>/edit/', views.card_edit, name='edit'),
path('<int:pk>/delete/', views.card_delete, name='delete'),
]
+73
View File
@@ -0,0 +1,73 @@
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 .forms import DinosaurForm
def is_htmx(request):
return request.headers.get('HX-Request') == 'true'
def card_list(request):
cards = Dinosaur.objects.all()
if is_htmx(request):
return render(request, 'cards/_cards_list.html', {'cards': cards})
return render(request, 'cards/list.html', {'cards': cards})
def card_create(request):
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)
# 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>'
return HttpResponse(card_html + oob)
return redirect('cards:list')
else:
if is_htmx(request):
# Return the form as an out-of-band fragment so it updates the form container
form_html = render_to_string('cards/_form.html', {'form': form}, request=request)
oob = f'<div id="htmx-form" hx-swap-oob="true">{form_html}</div>'
return HttpResponse(oob)
else:
form = DinosaurForm()
return render(request, 'cards/_form.html', {'form': form})
def card_edit(request, pk):
card = get_object_or_404(Dinosaur, pk=pk)
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)
# 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)
return redirect('cards:list')
else:
if is_htmx(request):
form_html = render_to_string('cards/_form.html', {'form': form, 'card': card}, request=request)
oob = f'<div id="htmx-form" hx-swap-oob="true">{form_html}</div>'
return HttpResponse(oob)
else:
form = DinosaurForm(instance=card)
return render(request, 'cards/_form.html', {'form': form, 'card': card})
def card_delete(request, pk):
card = get_object_or_404(Dinosaur, pk=pk)
if request.method == 'POST':
card.delete()
if is_htmx(request):
return HttpResponse(status=204)
return redirect('cards:list')
return HttpResponseBadRequest('Only POST allowed')
BIN
View File
Binary file not shown.
Executable
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'toptrumps.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
+2
View File
@@ -0,0 +1,2 @@
django
Pillow
+15
View File
@@ -0,0 +1,15 @@
<div class="card" id="card-{{ card.pk }}">
<h3>{{ card.name }}</h3>
<div><strong>Era:</strong> {{ card.get_era_display }} — <strong>Diet:</strong> {{ card.get_diet_display }}</div>
<div>{{ card.description|linebreaksbr }}</div>
<ul>
<li>Speed: {{ card.speed }}</li>
<li>Weight: {{ card.weight }}</li>
<li>Intelligence: {{ card.intelligence }}</li>
<li>Height: {{ card.height }}</li>
</ul>
<div>
<button hx-get="{% url 'cards:edit' card.pk %}" hx-target="#htmx-form" hx-swap="innerHTML">Edit</button>
<button hx-post="{% url 'cards:delete' card.pk %}" hx-confirm="Delete this card?" hx-swap="none">Delete</button>
</div>
</div>
+8
View File
@@ -0,0 +1,8 @@
{% load static %}
<div class="grid">
{% for card in cards %}
{% include 'cards/_card_item.html' with card=card %}
{% empty %}
<p>No dinosaurs yet — add one!</p>
{% endfor %}
</div>
+46
View File
@@ -0,0 +1,46 @@
<div class="card-form card">
{% if card %}
<form method="post" enctype="multipart/form-data" action="{% url 'cards:edit' card.pk %}" hx-post="{% url 'cards:edit' card.pk %}" hx-target="#card-{{ card.pk }}" hx-swap="outerHTML">
{% else %}
<form method="post" enctype="multipart/form-data" action="{% url 'cards:create' %}" hx-post="{% url 'cards:create' %}" hx-target="#cards-list .grid" hx-swap="afterbegin">
{% endif %}
{% csrf_token %}
{{ form.non_field_errors }}
<div class="row">
{{ form.name.label_tag }}<br>
{{ form.name }}
</div>
<div class="row">
{{ form.era.label_tag }}<br>
{{ form.era }}
</div>
<div class="row">
{{ form.diet.label_tag }}<br>
{{ form.diet }}
</div>
<div class="row">
{{ form.description.label_tag }}<br>
{{ form.description }}
</div>
<div class="row">
{{ form.image.label_tag }}<br>
{{ form.image }}
</div>
<div class="row">
{{ form.speed.label_tag }} {{ form.speed }}
</div>
<div class="row">
{{ form.weight.label_tag }} {{ form.weight }}
</div>
<div class="row">
{{ form.intelligence.label_tag }} {{ form.intelligence }}
</div>
<div class="row">
{{ form.height.label_tag }} {{ form.height }}
</div>
<div class="row">
<button type="submit">Save</button>
<button type="button" onclick="document.getElementById('htmx-form').innerHTML=''">Cancel</button>
</div>
</form>
</div>
+22
View File
@@ -0,0 +1,22 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>TopTrumps - Dinosaurs</title>
<script src="https://unpkg.com/htmx.org@1.9.5"></script>
<style>
body{font-family:system-ui,Segoe UI,Roboto,Arial;margin:20px}
.card{border:1px solid #ddd;padding:12px;margin:8px;border-radius:6px}
.controls{margin-bottom:12px}
.grid{display:flex;flex-wrap:wrap}
.grid .card{width:220px}
form .row{margin-bottom:8px}
</style>
</head>
<body>
<h1>TopTrumps — Dinosaurs</h1>
<div id="messages"></div>
{% block content %}{% endblock %}
</body>
</html>
+14
View File
@@ -0,0 +1,14 @@
{% extends 'cards/base.html' %}
{% block content %}
<div class="controls">
<button hx-get="{% url 'cards:create' %}" hx-target="#htmx-form" hx-swap="innerHTML">Add Dinosaur</button>
</div>
<div id="htmx-form"></div>
<div id="cards-list">
{% include 'cards/_cards_list.html' %}
</div>
{% endblock %}
View File
+16
View File
@@ -0,0 +1,16 @@
"""
ASGI config for toptrumps project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/6.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'toptrumps.settings')
application = get_asgi_application()
+122
View File
@@ -0,0 +1,122 @@
"""
Django settings for toptrumps project.
Generated by 'django-admin startproject' using Django 6.0.
For more information on this file, see
https://docs.djangoproject.com/en/6.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/6.0/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/6.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-411m+_g5(3vjb_%v*%au@s&np^)_-g!mp9v69(lys976%-m1j%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cards',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'toptrumps.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'toptrumps.wsgi.application'
# Database
# https://docs.djangoproject.com/en/6.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/6.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/6.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/6.0/howto/static-files/
STATIC_URL = 'static/'
# Media files (for uploaded dinosaur images)
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
+28
View File
@@ -0,0 +1,28 @@
"""
URL configuration for toptrumps project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/6.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('cards.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
+16
View File
@@ -0,0 +1,16 @@
"""
WSGI config for toptrumps project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/6.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'toptrumps.settings')
application = get_wsgi_application()