Initial import

This commit is contained in:
Joshua Laymon 2025-08-12 20:50:46 -05:00
commit e6cb7e91aa
29 changed files with 886 additions and 0 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

6
.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
.env
staticfiles/
db_data/
__pycache__/
*.pyc
imports/

24
docker-compose.yml Normal file
View File

@ -0,0 +1,24 @@
version: "3.9"
services:
web:
build: ./web
env_file:
- .env
volumes:
- ./web:/app
- ./imports:/data/imports
ports:
- "8000:8000"
depends_on:
- db
db:
image: postgres:16-alpine
environment:
POSTGRES_DB: illustrations
POSTGRES_USER: illustrations
POSTGRES_PASSWORD: illustrations
volumes:
- db_data:/var/lib/postgresql/data
volumes:
db_data:

BIN
web/.DS_Store vendored Normal file

Binary file not shown.

16
web/Dockerfile Normal file
View File

@ -0,0 +1,16 @@
FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
WORKDIR /app
RUN apt-get update && apt-get install -y build-essential libpq-dev && rm -rf /var/lib/apt/lists/*
COPY requirements.txt /app/
RUN pip install --no-cache-dir -r requirements.txt
COPY . /app/
CMD ["bash", "-lc", "python manage.py migrate && python manage.py init_users && python manage.py runserver 0.0.0.0:8000"]

0
web/core/__init__.py Normal file
View File

13
web/core/admin.py Normal file
View File

@ -0,0 +1,13 @@
from django.contrib import admin
from .models import Entry, ScriptureRef
class ScriptureInline(admin.TabularInline):
model = ScriptureRef
extra = 0
@admin.register(Entry)
class EntryAdmin(admin.ModelAdmin):
list_display = ("talk_title","entry_code","source","date_added","date_edited")
search_fields = ("talk_title","entry_code","source","subject","illustration","application","scripture_raw")
inlines = [ScriptureInline]

5
web/core/apps.py Normal file
View File

@ -0,0 +1,5 @@
from django.apps import AppConfig
class CoreConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "core"

6
web/core/forms.py Normal file
View File

@ -0,0 +1,6 @@
from django import forms
class ImportForm(forms.Form):
file = forms.FileField(allow_empty_file=False)
dry_run = forms.BooleanField(initial=True, required=False, help_text="Preview changes without saving")

View File

View File

View File

@ -0,0 +1,27 @@
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
import os
class Command(BaseCommand):
def handle(self, *args, **kwargs):
admin_user = os.getenv("INIT_ADMIN_USERNAME")
admin_pass = os.getenv("INIT_ADMIN_PASSWORD")
editor_user = os.getenv("INIT_EDITOR_USERNAME")
editor_pass = os.getenv("INIT_EDITOR_PASSWORD")
if admin_user and admin_pass:
u, created = User.objects.get_or_create(username=admin_user)
u.is_staff = True
u.is_superuser = True
if admin_pass:
u.set_password(admin_pass)
u.save()
self.stdout.write(self.style.SUCCESS(f"Admin ready: {admin_user}"))
if editor_user and editor_pass:
u, created = User.objects.get_or_create(username=editor_user)
u.is_staff = False
u.is_superuser = False
if editor_pass:
u.set_password(editor_pass)
u.save()
self.stdout.write(self.style.SUCCESS(f"Editor ready: {editor_user}"))

View File

@ -0,0 +1,39 @@
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name='Entry',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('subject', models.TextField(blank=True)),
('illustration', models.TextField(blank=True)),
('application', models.TextField(blank=True)),
('scripture_raw', models.TextField(blank=True)),
('source', models.CharField(blank=True, max_length=255)),
('talk_title', models.CharField(blank=True, max_length=255)),
('talk_number', models.IntegerField(blank=True, null=True)),
('entry_code', models.CharField(blank=True, db_index=True, max_length=64)),
('date_added', models.DateField(blank=True, null=True)),
('date_edited', models.DateField(blank=True, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
],
),
migrations.CreateModel(
name='ScriptureRef',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('book', models.CharField(max_length=32)),
('chapter_from', models.IntegerField(blank=True, null=True)),
('verse_from', models.IntegerField(blank=True, null=True)),
('chapter_to', models.IntegerField(blank=True, null=True)),
('verse_to', models.IntegerField(blank=True, null=True)),
('entry', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scripture_refs', to='core.entry')),
],
),
]

View File

32
web/core/models.py Normal file
View File

@ -0,0 +1,32 @@
from django.db import models
class Entry(models.Model):
# Field names aligned to CSV headers (case-insensitive mapping in importer)
subject = models.TextField(blank=True)
illustration = models.TextField(blank=True)
application = models.TextField(blank=True)
scripture_raw = models.TextField(blank=True) # from CSV 'Scripture'
source = models.CharField(max_length=255, blank=True)
talk_title = models.CharField(max_length=255, blank=True) # 'Talk Title'
talk_number = models.IntegerField(null=True, blank=True) # 'Talk Number'
entry_code = models.CharField(max_length=64, blank=True, db_index=True) # 'Code'
date_added = models.DateField(null=True, blank=True) # 'Date'
date_edited = models.DateField(null=True, blank=True) # 'Date Edited'
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.talk_title or '(untitled)'} [{self.entry_code}]"
class ScriptureRef(models.Model):
entry = models.ForeignKey(Entry, on_delete=models.CASCADE, related_name="scripture_refs")
book = models.CharField(max_length=32)
chapter_from = models.IntegerField(null=True, blank=True)
verse_from = models.IntegerField(null=True, blank=True)
chapter_to = models.IntegerField(null=True, blank=True)
verse_to = models.IntegerField(null=True, blank=True)
def __str__(self):
return f"{self.book} {self.chapter_from}:{self.verse_from}"

163
web/core/utils.py Normal file
View File

@ -0,0 +1,163 @@
import csv, io, re
from datetime import datetime
from dateutil import parser as dateparser
from django.db.models import Q
from .models import Entry, ScriptureRef
# Scripture parsing --------------------------------------------------
BOOK_ALIASES = {
"gen":"Genesis","ge":"Genesis","ex":"Exodus","lev":"Leviticus","num":"Numbers","deut":"Deuteronomy",
"josh":"Joshua","judg":"Judges","rut":"Ruth","1sam":"1 Samuel","2sam":"2 Samuel",
"1kings":"1 Kings","2kings":"2 Kings","1chron":"1 Chronicles","2chron":"2 Chronicles",
"ezra":"Ezra","neh":"Nehemiah","esth":"Esther","job":"Job","ps":"Psalms","psa":"Psalms","prov":"Proverbs",
"eccl":"Ecclesiastes","song":"Song of Solomon","isa":"Isaiah","jer":"Jeremiah","lam":"Lamentations",
"ezek":"Ezekiel","dan":"Daniel","hos":"Hosea","joel":"Joel","amos":"Amos","obad":"Obadiah",
"jon":"Jonah","mic":"Micah","nah":"Nahum","hab":"Habakkuk","zeph":"Zephaniah","hag":"Haggai",
"zech":"Zechariah","mal":"Malachi","matt":"Matthew","mt":"Matthew","mark":"Mark","mk":"Mark","lk":"Luke",
"luke":"Luke","jn":"John","john":"John","acts":"Acts","rom":"Romans","1cor":"1 Corinthians",
"2cor":"2 Corinthians","gal":"Galatians","eph":"Ephesians","phil":"Philippians","col":"Colossians",
"1thess":"1 Thessalonians","2thess":"2 Thessalonians","1tim":"1 Timothy","2tim":"2 Timothy",
"titus":"Titus","phlm":"Philemon","heb":"Hebrews","jas":"James","jam":"James","1pet":"1 Peter","2pet":"2 Peter",
"1john":"1 John","2john":"2 John","3john":"3 John","jude":"Jude","rev":"Revelation","re":"Revelation",
}
SCR_REF_RE = re.compile(r"""
^\s*([1-3]?\s*[A-Za-z\.]+)\s+ # book
(\d+) # chapter start
(?::(\d+))? # verse start
(?:\s*[-]\s*(\d+)(?::(\d+))?)? # optional range
\s*$
""", re.VERBOSE)
def normalize_book(book_raw:str) -> str:
b = re.sub(r"[\.\s]","", book_raw).lower()
return BOOK_ALIASES.get(b, book_raw.strip())
def parse_scripture(s: str):
parts = [p.strip() for p in (s or "").split(";") if p.strip()]
parsed = []
for p in parts:
m = SCR_REF_RE.match(p)
if not m:
parsed.append(None); continue
book_raw, ch1, v1, ch2, v2 = m.groups()
parsed.append({
"book": normalize_book(book_raw),
"chapter_from": int(ch1),
"verse_from": int(v1) if v1 else None,
"chapter_to": int(ch2) if ch2 else None,
"verse_to": int(v2) if v2 else None,
})
return parsed
# CSV import ---------------------------------------------------------
EXPECTED_HEADERS = ["Subject","Illustration","Application","Scripture","Source","Talk Title","Talk Number","Code","Date","Date Edited"]
def parse_date(value):
if not value or not str(value).strip(): return None
try: return dateparser.parse(str(value)).date()
except Exception: return None
def import_csv(file_bytes: bytes, dry_run: bool=True):
text = file_bytes.decode("utf-8-sig")
reader = csv.DictReader(io.StringIO(text))
headers = reader.fieldnames or []
# normalize
lower_map = {h.lower():h for h in headers}
required_lower = [h.lower() for h in EXPECTED_HEADERS]
missing = [orig for orig in EXPECTED_HEADERS if orig.lower() not in lower_map]
if missing:
raise ValueError(f"Missing required headers: {missing}")
report = {"rows":0,"inserted":0,"updated":0,"skipped":0,"errors":[],"scripture_parsed":0,"scripture_failed":0}
rows = list(reader); report["rows"] = len(rows)
for r in rows:
try:
def get(name):
return r[ lower_map[name.lower()] ].strip() if r.get(lower_map[name.lower()]) is not None else ""
entry_code = get("Code")
data = dict(
subject=get("Subject"),
illustration=get("Illustration"),
application=get("Application"),
scripture_raw=get("Scripture"),
source=get("Source"),
talk_title=get("Talk Title"),
talk_number=int(get("Talk Number")) if get("Talk Number") else None,
entry_code=entry_code,
date_added=parse_date(get("Date")),
date_edited=parse_date(get("Date Edited")),
)
obj = None
if entry_code:
try: obj = Entry.objects.get(entry_code=entry_code)
except Entry.DoesNotExist: obj = None
if not dry_run:
if obj:
for k,v in data.items(): setattr(obj,k,v)
obj.save()
obj.scripture_refs.all().delete()
report["updated"] += 1
else:
obj = Entry.objects.create(**data)
report["inserted"] += 1
for pr in parse_scripture(data["scripture_raw"]):
if pr: ScriptureRef.objects.create(entry=obj, **pr); report["scripture_parsed"] += 1
else: report["scripture_failed"] += 1
else:
for pr in parse_scripture(data["scripture_raw"]):
if pr: report["scripture_parsed"] += 1
else: report["scripture_failed"] += 1
except Exception as e:
report["skipped"] += 1
report["errors"].append(str(e))
return report
# Search helpers -----------------------------------------------------
SEARCHABLE_FIELDS = {
"Subject": "subject",
"Illustration": "illustration",
"Application": "application",
"Scripture": "scripture_raw",
"Source": "source",
"Talk Title": "talk_title",
"Talk Number": "talk_number",
"Code": "entry_code",
}
def wildcard_to_ilike(term:str)->str:
# Convert * ? to SQL ILIKE pattern
return term.replace('%','\%').replace('_','\_').replace('*','%').replace('?','_')
def build_query(selected_fields, query_text):
# Split on spaces unless inside quotes
tokens = []
buf = ''
in_quotes = False
for ch in query_text:
if ch == '"': in_quotes = not in_quotes; continue
if ch.isspace() and not in_quotes:
if buf: tokens.append(buf); buf=''
else:
buf += ch
if buf: tokens.append(buf)
# Build Q objects: AND across tokens, OR across fields for each token
q = Q()
for t in tokens:
pat = wildcard_to_ilike(t)
token_q = Q()
# OR across fields
for label in selected_fields:
col = SEARCHABLE_FIELDS[label]
if col == "talk_number" and pat.replace('%','').replace('_','').isdigit():
try:
token_q |= Q(**{col: int(pat.replace('%','').replace('_',''))})
except: pass
else:
token_q |= Q(**{f"{col}__icontains": t.replace('*','').replace('?','')}) | Q(**{f"{col}__iregex": pat.replace('%','.*').replace('_','.')})
q &= token_q
return q

176
web/core/views.py Normal file
View File

@ -0,0 +1,176 @@
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required, user_passes_test
from django.http import HttpResponse, HttpResponseForbidden
from django.contrib import messages
from django.db.models import Q
import csv
from django.utils.timezone import now
from .forms import ImportForm
from .models import Entry
from .utils import import_csv, SEARCHABLE_FIELDS, build_query
def is_admin(user):
return user.is_superuser or user.is_staff
def login_view(request):
if request.user.is_authenticated:
return redirect("search")
ctx = {}
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
user = authenticate(request, username=username, password=password)
if user:
login(request, user)
return redirect("search")
ctx["error"] = "Invalid credentials"
return render(request, "login.html", ctx)
@login_required
def redirect_to_search(request):
return redirect("search")
@login_required
def search_view(request):
total = Entry.objects.count()
query = request.GET.get("q", "").strip()
selected = request.GET.getlist("fields") or list(SEARCHABLE_FIELDS.keys())
entries = []
results_count = 0
current_id = None
if query:
q = build_query(selected, query)
entries = list(Entry.objects.filter(q).order_by("-date_added","-id").values_list("id", flat=True))
results_count = len(entries)
request.session["search_ids"] = entries
request.session["search_index"] = 0
if entries:
current_id = entries[0]
return redirect("record_view", entry_id=current_id)
return render(request, "search.html", {
"total": total,
"q": query,
"selected": selected,
"fields": list(SEARCHABLE_FIELDS.keys()),
"results_count": results_count,
})
@login_required
def record_view(request, entry_id):
ids = request.session.get("search_ids", [])
if entry_id in ids:
request.session["search_index"] = ids.index(entry_id)
idx = request.session.get("search_index", 0)
total = Entry.objects.count()
results_count = len(ids)
pos = (idx+1) if ids else 1
entry = get_object_or_404(Entry, id=entry_id)
return render(request, "record.html", {
"entry": entry,
"locked": True,
"total": total,
"results_count": results_count,
"position": pos,
})
@login_required
def nav_prev(request):
ids = request.session.get("search_ids", [])
idx = request.session.get("search_index", 0)
if ids:
idx = max(0, idx-1)
request.session["search_index"] = idx
return redirect("record_view", entry_id=ids[idx])
messages.info(request, "No search results loaded.")
return redirect("search")
@login_required
def nav_next(request):
ids = request.session.get("search_ids", [])
idx = request.session.get("search_index", 0)
if ids:
idx = min(len(ids)-1, idx+1)
request.session["search_index"] = idx
return redirect("record_view", entry_id=ids[idx])
messages.info(request, "No search results loaded.")
return redirect("search")
@login_required
def record_save(request, entry_id):
if request.method != "POST":
return redirect("record_view", entry_id=entry_id)
e = get_object_or_404(Entry, id=entry_id)
# Save edited fields
e.subject = request.POST.get("subject","")
e.illustration = request.POST.get("illustration","")
e.application = request.POST.get("application","")
e.scripture_raw = request.POST.get("scripture_raw","")
e.source = request.POST.get("source","")
e.talk_title = request.POST.get("talk_title","")
tn = request.POST.get("talk_number","").strip()
e.talk_number = int(tn) if tn.isdigit() else None
e.entry_code = request.POST.get("entry_code","")
e.date_added = request.POST.get("date_added") or None
e.date_edited = request.POST.get("date_edited") or None
e.save()
messages.success(request, "Saved changes.")
return redirect("record_view", entry_id=entry_id)
@login_required
def record_delete(request, entry_id):
if request.method == "POST":
e = get_object_or_404(Entry, id=entry_id)
e.delete()
messages.success(request, "Entry deleted.")
# After delete, move to previous or search page
ids = request.session.get("search_ids", [])
idx = request.session.get("search_index", 0)
if ids:
ids = [i for i in ids if i != entry_id]
request.session["search_ids"] = ids
if not ids:
return redirect("search")
idx = max(0, min(idx, len(ids)-1))
request.session["search_index"] = idx
return redirect("record_view", entry_id=ids[idx])
return redirect("search")
return HttpResponseForbidden("Use POST to delete.")
@login_required
@user_passes_test(is_admin)
def import_wizard(request):
from .forms import ImportForm
if request.method == "POST":
form = ImportForm(request.POST, request.FILES)
if form.is_valid():
fbytes = form.cleaned_data["file"].read()
dry = form.cleaned_data["dry_run"]
try:
report = import_csv(fbytes, dry_run=dry)
return render(request, "import_result.html", {"report": report, "dry_run": dry})
except Exception as e:
messages.error(request, f"Import failed: {e}")
else:
form = ImportForm()
return render(request, "import_wizard.html", {"form": form})
@login_required
@user_passes_test(is_admin)
def export_csv(request):
response = HttpResponse(content_type='text/csv')
ts = now().strftime("%Y-%m-%d_%H-%M-%S")
response['Content-Disposition'] = f'attachment; filename="illustrations_backup_{ts}.csv"'
writer = csv.writer(response)
writer.writerow(["Subject","Illustration","Application","Scripture","Source","Talk Title","Talk Number","Code","Date","Date Edited"])
for e in Entry.objects.all().order_by("id"):
writer.writerow([
e.subject, e.illustration, e.application, e.scripture_raw, e.source,
e.talk_title, e.talk_number if e.talk_number is not None else "", e.entry_code,
e.date_added.isoformat() if e.date_added else "",
e.date_edited.isoformat() if e.date_edited else "",
])
return response

View File

View File

@ -0,0 +1,80 @@
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", "dev-insecure")
DEBUG = os.getenv("DJANGO_DEBUG","False") == "True"
ALLOWED_HOSTS = os.getenv("DJANGO_ALLOWED_HOSTS","").split(",") if os.getenv("DJANGO_ALLOWED_HOSTS") else ["*"]
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"core",
]
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 = "illustrations.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / "templates"],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "illustrations.wsgi.application"
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "illustrations",
"USER": "illustrations",
"PASSWORD": "illustrations",
"HOST": "db",
"PORT": 5432,
}
}
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"},
]
LANGUAGE_CODE = "en-us"
TIME_ZONE = "America/Chicago"
USE_I18N = True
USE_TZ = True
STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [BASE_DIR / "static"]
LOGIN_URL = "/login/"
LOGIN_REDIRECT_URL = "/search/"
LOGOUT_REDIRECT_URL = "/login/"

20
web/illustrations/urls.py Normal file
View File

@ -0,0 +1,20 @@
from django.contrib import admin
from django.urls import path
from django.contrib.auth import views as auth_views
from core import views as core_views
urlpatterns = [
path("admin/", admin.site.urls),
path("login/", core_views.login_view, name="login"),
path("logout/", auth_views.LogoutView.as_view(), name="logout"),
path("", core_views.redirect_to_search),
path("search/", core_views.search_view, name="search"),
path("record/<int:entry_id>/", core_views.record_view, name="record_view"),
path("record/<int:entry_id>/save/", core_views.record_save, name="record_save"),
path("record/<int:entry_id>/delete/", core_views.record_delete, name="record_delete"),
path("nav/prev/", core_views.nav_prev, name="nav_prev"),
path("nav/next/", core_views.nav_next, name="nav_next"),
path("import/", core_views.import_wizard, name="import_wizard"),
path("export/csv/", core_views.export_csv, name="export_csv"),
]

View File

@ -0,0 +1,5 @@
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'illustrations.settings')
application = get_wsgi_application()

9
web/manage.py Normal file
View File

@ -0,0 +1,9 @@
#!/usr/bin/env python
import os, sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'illustrations.settings')
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

4
web/requirements.txt Normal file
View File

@ -0,0 +1,4 @@
Django==5.0.6
psycopg2-binary==2.9.9
python-dateutil==2.9.0.post0

56
web/templates/base.html Normal file
View File

@ -0,0 +1,56 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{% block title %}Illustrations DB{% endblock %}</title>
<style>
:root {
--blue:#1f6cd8;
--light:#f6f8fb;
--panel:#ffffff;
--line:#e5e9f2;
--text:#1a1a1a;
--muted:#6b7280;
}
body { margin:0; font-family: system-ui, -apple-system, Segoe UI, Roboto, Noto Sans, Ubuntu, Cantarell, Helvetica, Arial, sans-serif; background:var(--light); color:var(--text); }
.topbar { display:flex; align-items:center; justify-content:space-between; padding:12px 16px; background:#fff; border-bottom:1px solid var(--line); position:sticky; top:0; z-index:10;}
.brand { font-weight:700; color:var(--blue); letter-spacing:.2px; }
.menu a { margin-left:14px; text-decoration:none; color:var(--blue); }
.container { max-width: 1100px; margin: 24px auto; padding: 0 16px; }
.panel { background:var(--panel); border:1px solid var(--line); border-radius:12px; box-shadow: 0 8px 20px rgba(0,0,0,0.04); padding: 18px; }
.btn { display:inline-block; padding:10px 14px; border-radius:10px; border:1px solid var(--line); background:#fff; color:#0d1b2a; text-decoration:none; cursor:pointer; }
.btn.primary { background:var(--blue); color:#fff; border-color:var(--blue); }
.btn.danger { background:#d61f1f; color:#fff; border-color:#d61f1f; }
.flash { margin: 16px 0; padding: 12px; border-radius:10px; background:#eaf2ff; color:#0b3d91; }
input[type=text], input[type=password], input[type=date], textarea { width:100%; padding:10px; border:1px solid var(--line); border-radius:10px; background:#fff; }
label { font-size: 13px; color:#333; display:block; margin-bottom:6px; }
.row { display:grid; grid-template-columns: 1fr 1fr; gap:16px; }
.row3 { display:grid; grid-template-columns: 1fr 1fr 1fr; gap:16px; }
.muted { color: var(--muted); }
@media (max-width: 900px){ .row, .row3{ grid-template-columns: 1fr; } }
.stats { display:flex; gap:12px; align-items:center; font-size:14px; color:var(--muted); }
.nav { display:flex; gap:8px; align-items:center; }
</style>
</head>
<body>
{% if request.user.is_authenticated %}
<div class="topbar">
<div class="brand">Illustrations Database</div>
<div class="menu">
<a href="/search/">Search</a>
{% if request.user.is_staff %}
<a href="/import/">Import Data</a>
<a href="/export/csv/">Download Backup</a>
{% endif %}
<a href="/logout/">Logout</a>
</div>
</div>
{% endif %}
<div class="container">
{% for message in messages %}<div class="flash">{{ message }}</div>{% endfor %}
{% block content %}{% endblock %}
</div>
</body>
</html>

View File

@ -0,0 +1,24 @@
{% extends "base.html" %}
{% block title %}Import Result - Illustrations DB{% endblock %}
{% block content %}
<div class="panel">
<h2 style="margin-top:0;">Import {{ "Preview" if dry_run else "Result" }}</h2>
<ul>
<li>Total rows: <strong>{{ report.rows }}</strong></li>
<li>Inserted: <strong>{{ report.inserted }}</strong></li>
<li>Updated: <strong>{{ report.updated }}</strong></li>
<li>Skipped: <strong>{{ report.skipped }}</strong></li>
<li>Scripture parsed: <strong>{{ report.scripture_parsed }}</strong></li>
<li>Scripture failed: <strong>{{ report.scripture_failed }}</strong></li>
</ul>
{% if report.errors and report.errors|length %}
<h3>Errors</h3>
<pre style="white-space:pre-wrap;">{{ report.errors|join("\n") }}</pre>
{% endif %}
<div style="margin-top:16px;">
<a class="btn" href="/import/">Run again</a>
<a class="btn" href="/search/">Done</a>
</div>
</div>
{% endblock %}

View File

@ -0,0 +1,25 @@
{% extends "base.html" %}
{% block title %}Import Data - Illustrations DB{% endblock %}
{% block content %}
<div class="panel">
<h2 style="margin-top:0;">Import Data (CSV)</h2>
<p>Expected headers (any order, case-insensitive): <code>Subject, Illustration, Application, Scripture, Source, Talk Title, Talk Number, Code, Date, Date Edited</code></p>
<form method="post" enctype="multipart/form-data">{% csrf_token %}
<div class="row">
<div>
<label>CSV file</label>
{{ form.file }}
</div>
<div>
<label>{{ form.dry_run.label }}</label>
{{ form.dry_run }} <small>{{ form.dry_run.help_text }}</small>
</div>
</div>
<div style="margin-top:16px; display:flex; gap:10px; justify-content:flex-end;">
<a class="btn" href="/search/">Cancel</a>
<button class="btn primary" type="submit">Process</button>
</div>
</form>
</div>
{% endblock %}

19
web/templates/login.html Normal file
View File

@ -0,0 +1,19 @@
{% extends "base.html" %}
{% block title %}Sign in - Illustrations DB{% endblock %}
{% block content %}
<div class="panel" style="max-width:420px; margin: 80px auto;">
<h2 style="margin-top:0; color: var(--blue);">Sign in</h2>
{% if error %}<div class="flash">{{ error }}</div>{% endif %}
<form method="post">{% csrf_token %}
<label>Username</label>
<input type="text" name="username" required />
<label style="margin-top:12px;">Password</label>
<input type="password" name="password" required />
<div style="margin-top:16px; display:flex; gap:10px; justify-content:flex-end;">
<a class="btn" href="#">Cancel</a>
<button class="btn primary" type="submit">Sign in</button>
</div>
</form>
</div>
{% endblock %}

101
web/templates/record.html Normal file
View File

@ -0,0 +1,101 @@
{% extends "base.html" %}
{% block title %}Record - Illustrations DB{% endblock %}
{% block content %}
<div class="stats" style="margin-bottom:8px;">
<div>Total: <strong>{{ total }}</strong></div>
<div>Results: <strong>{{ results_count }}</strong></div>
<div>Viewing: <strong>{{ position }}</strong> of <strong>{{ results_count|default:1 }}</strong></div>
</div>
<div class="panel">
<div style="display:flex; justify-content:space-between; align-items:center;">
<div class="nav">
<a class="btn" href="/nav/prev/">&larr; Prev</a>
<a class="btn" href="/nav/next/">Next &rarr;</a>
</div>
<div>
<button class="btn" id="unlockBtn">Unlock to Edit</button>
<form method="post" action="/record/{{ entry.id }}/delete/" style="display:inline;" onsubmit="return confirm('Are you sure you want to permanently delete this entry?');">
{% csrf_token %}
<button class="btn danger">Delete</button>
</form>
</div>
</div>
<form id="entryForm" method="post" action="/record/{{ entry.id }}/save/" style="margin-top:14px;">
{% csrf_token %}
<div class="row">
<div>
<label>Subject</label>
<input type="text" name="subject" value="{{ entry.subject|default:'' }}" readonly />
</div>
<div>
<label>Scripture</label>
<input type="text" name="scripture_raw" value="{{ entry.scripture_raw|default:'' }}" readonly />
</div>
</div>
<div style="margin-top:12px;">
<label>Illustration</label>
<textarea name="illustration" rows="5" readonly>{{ entry.illustration|default:'' }}</textarea>
</div>
<div style="margin-top:12px;">
<label>Application</label>
<textarea name="application" rows="5" readonly>{{ entry.application|default:'' }}</textarea>
</div>
<div class="row3" style="margin-top:12px;">
<div>
<label>Source</label>
<input type="text" name="source" value="{{ entry.source|default:'' }}" readonly />
</div>
<div>
<label>Talk Number</label>
<input type="text" name="talk_number" value="{{ entry.talk_number|default:'' }}" readonly />
</div>
<div>
<label>Code</label>
<input type="text" name="entry_code" value="{{ entry.entry_code|default:'' }}" readonly />
</div>
</div>
<div class="row" style="margin-top:12px;">
<div>
<label>Talk Title</label>
<input type="text" name="talk_title" value="{{ entry.talk_title|default:'' }}" readonly />
</div>
<div class="row" style="grid-template-columns: 1fr 1fr; gap:12px;">
<div>
<label>Date</label>
<input type="text" name="date_added" value="{{ entry.date_added|default:'' }}" readonly />
</div>
<div>
<label>Date Edited</label>
<input type="text" name="date_edited" value="{{ entry.date_edited|default:'' }}" readonly />
</div>
</div>
</div>
<div style="margin-top:16px; display:flex; gap:10px; justify-content:flex-end;">
<a class="btn" href="/search/">Back to Search</a>
<button class="btn primary" id="saveBtn" type="submit" disabled>Save Changes</button>
</div>
</form>
</div>
<script>
const unlockBtn = document.getElementById('unlockBtn');
const form = document.getElementById('entryForm');
const saveBtn = document.getElementById('saveBtn');
unlockBtn.addEventListener('click', function(){
form.querySelectorAll('input, textarea').forEach(el=>{
if(el.name !== 'csrfmiddlewaretoken'){ el.removeAttribute('readonly'); }
});
saveBtn.disabled = false;
unlockBtn.disabled = true;
unlockBtn.textContent = 'Unlocked';
});
</script>
{% endblock %}

36
web/templates/search.html Normal file
View File

@ -0,0 +1,36 @@
{% extends "base.html" %}
{% block title %}Search - Illustrations DB{% endblock %}
{% block content %}
<div class="panel">
<form method="get" action="/search/">
<div class="row">
<div>
<label>Search (supports * and ?)</label>
<input type="text" name="q" value="{{ q|default:'' }}" placeholder="e.g., Default, Organization or Matt 12:30 or *loyal*" />
</div>
<div>
<label>Fields to search</label>
<div style="display:grid; grid-template-columns: 1fr 1fr; gap:6px; padding-top:6px;">
{% for f in fields %}
<label><input type="checkbox" name="fields" value="{{ f }}" {% if f in selected %}checked{% endif %}> {{ f }}</label>
{% endfor %}
</div>
</div>
</div>
<div style="margin-top:12px; display:flex; gap:10px; justify-content:flex-end;">
<a class="btn" href="/search/">Clear</a>
<button class="btn primary" type="submit">Search</button>
</div>
</form>
</div>
<div class="stats" style="margin-top:12px;">
<div>Total entries: <strong>{{ total }}</strong></div>
{% if results_count %}<div>Results: <strong>{{ results_count }}</strong></div>{% endif %}
</div>
{% if results_count %}
<div class="panel" style="margin-top:12px;">
<p>Opening first result…</p>
</div>
{% endif %}
{% endblock %}