stuff is working again

This commit is contained in:
2025-06-26 05:21:21 -05:00
parent 7a8ec5face
commit 00fd49c79b
12 changed files with 639 additions and 272 deletions

View File

@ -82,6 +82,7 @@ class Plant(db.Model):
plant_type = db.Column(db.String(50), nullable=False)
notes = db.Column(db.Text, nullable=True)
short_id = db.Column(db.String(8), unique=True, nullable=True, index=True)
vendor_name = db.Column(db.String(255), nullable=True)
price = db.Column(db.Numeric(10, 2), nullable=True)
@ -151,3 +152,16 @@ class Plant(db.Model):
def __repr__(self):
return f"<Plant {self.uuid} ({self.plant_type})>"
@classmethod
def generate_short_id(cls, length: int = 6) -> str:
"""
Produce a random [az09] string of the given length
and ensure it doesnt collide with any existing plant.short_id.
"""
alphabet = string.ascii_lowercase + string.digits
while True:
candidate = ''.join(random.choices(alphabet, k=length))
# Check uniqueness
if not cls.query.filter_by(short_id=candidate).first():
return candidate

View File

@ -1,5 +1,6 @@
from uuid import uuid4
import os
import string
from sqlalchemy.orm import joinedload
from flask import (
@ -14,7 +15,7 @@ from flask import (
from flask_login import login_required, current_user
from app import db
from .models import Plant, PlantCommonName, PlantScientificName
from .models import Plant, PlantScientificName, PlantCommonName
from .forms import PlantForm
from plugins.media.models import Media
from plugins.media.routes import (
@ -76,11 +77,10 @@ def index():
stats=stats,
)
@bp.route('/create', methods=['GET', 'POST'])
@bp.route('/', methods=['GET', 'POST'])
@login_required
def create():
form = PlantForm()
form.plant_type.choices = [
('plant', 'Plant'),
('cutting', 'Cutting'),
@ -96,13 +96,6 @@ def create():
(s.id, s.name)
for s in PlantScientificName.query.order_by(PlantScientificName.name).all()
]
form.mother_uuid.choices = [('N/A', 'None')] + [
(
p.uuid,
f"{p.common_name.name if p.common_name else 'Unnamed'} {p.uuid}"
)
for p in Plant.query.order_by(Plant.created_at.desc()).all()
]
if form.validate_on_submit():
new_plant = Plant(
@ -111,11 +104,7 @@ def create():
plant_type=form.plant_type.data,
common_id=form.common_name.data,
scientific_id=form.scientific_name.data,
mother_uuid=(
form.mother_uuid.data
if form.mother_uuid.data != 'N/A'
else None
),
mother_uuid=(form.mother_uuid.data if form.mother_uuid.data != 'N/A' else None),
custom_slug=(form.custom_slug.data.strip() or None),
vendor_name=(form.vendor_name.data.strip() or None),
price=(form.price.data or None),
@ -130,25 +119,97 @@ def create():
return render_template('plant/create.html', form=form)
@bp.route('/<uuid:uuid_val>', methods=['GET'])
@login_required
def detail(uuid_val):
plant = Plant.query.filter_by(
uuid=str(uuid_val),
owner_id=current_user.id,
).first_or_404()
return render_template('plant/detail.html', plant=plant)
# 1) load this plant (and its media) or 404
plant = (
Plant.query
.options(joinedload(Plant.media_items))
.filter_by(uuid=str(uuid_val), owner_id=current_user.id)
.first_or_404()
)
# 2) load any child plants (same owner, mother_uuid pointing here)
children = (
Plant.query
.options(joinedload(Plant.media_items))
.filter_by(owner_id=current_user.id, mother_uuid=plant.uuid)
.order_by(Plant.id)
.all()
)
# 3) build linear nav of this user's plants (by insertion order)
all_plants = (
Plant.query
.filter_by(owner_id=current_user.id)
.order_by(Plant.id)
.all()
)
uuids = [p.uuid for p in all_plants]
try:
idx = uuids.index(str(uuid_val))
except ValueError:
idx = None
prev_uuid = uuids[idx - 1] if idx not in (None, 0) else None
next_uuid = uuids[idx + 1] if idx is not None and idx < len(uuids) - 1 else None
return render_template(
'plant/detail.html',
plant=plant,
children=children,
prev_uuid=prev_uuid,
next_uuid=next_uuid
)
@bp.route('/<uuid:uuid_val>/generate_children', methods=['POST'])
@login_required
def generate_children(uuid_val):
parent = (
Plant.query
.filter_by(uuid=str(uuid_val), owner_id=current_user.id)
.first_or_404()
)
try:
count = int(request.form.get('count', 1))
except ValueError:
count = 1
created = 0
for _ in range(count):
child = Plant(
uuid=str(uuid4()),
owner_id=current_user.id,
plant_type='cutting',
common_id=parent.common_id,
scientific_id=parent.scientific_id,
mother_uuid=parent.uuid,
custom_slug=None,
vendor_name=None,
price=None,
notes=None,
data_verified=False,
is_active=True
)
db.session.add(child)
created += 1
db.session.commit()
flash(f"Generated {created} cuttings for {parent.common_name.name}.", 'success')
return redirect(url_for('plant.detail', uuid_val=parent.uuid))
@bp.route('/<uuid:uuid_val>/edit', methods=['GET', 'POST'])
@login_required
def edit(uuid_val):
plant = Plant.query.filter_by(
uuid=str(uuid_val),
owner_id=current_user.id,
owner_id=current_user.id
).first_or_404()
form = PlantForm()
form.plant_type.choices = [
('plant', 'Plant'),
('cutting', 'Cutting'),
@ -165,10 +226,7 @@ def edit(uuid_val):
for s in PlantScientificName.query.order_by(PlantScientificName.name).all()
]
form.mother_uuid.choices = [('N/A', 'None')] + [
(
p.uuid,
f"{p.common_name.name if p.common_name else 'Unnamed'} {p.uuid}"
)
(p.uuid, f"{p.common_name.name if p.common_name else 'Unnamed'} {p.uuid}")
for p in Plant.query.filter(Plant.uuid != plant.uuid).all()
]
@ -188,22 +246,15 @@ def edit(uuid_val):
plant.plant_type = form.plant_type.data
plant.common_id = form.common_name.data
plant.scientific_id = form.scientific_name.data
plant.mother_uuid = (
form.mother_uuid.data
if form.mother_uuid.data != 'N/A'
else None
)
plant.mother_uuid = (form.mother_uuid.data if form.mother_uuid.data != 'N/A' else None)
plant.custom_slug = (form.custom_slug.data.strip() or None)
plant.vendor_name = (form.vendor_name.data.strip() or None)
plant.price = (form.price.data or None)
plant.price = form.price.data or None
plant.notes = form.notes.data
plant.data_verified = form.data_verified.data
plant.is_active = form.is_active.data
# — patch to save whichever radio was checked —
featured_id = request.form.get("featured_media_id")
if featured_id and featured_id.isdigit():
plant.featured_media_id = int(featured_id)
# (No more inline "featured_media_id" patch here—handled in media plugin)
db.session.commit()
flash('Plant updated successfully.', 'success')
@ -211,32 +262,32 @@ def edit(uuid_val):
return render_template('plant/edit.html', form=form, plant=plant)
@bp.route('/<uuid:uuid_val>/upload', methods=['POST'])
@login_required
def upload_image(uuid_val):
plant = Plant.query.filter_by(uuid=str(uuid_val)).first_or_404()
file = request.files.get('file')
if file and file.filename:
save_media_file(
file,
current_user.id,
related_model='plant',
related_uuid=str(plant.uuid),
)
flash('Image uploaded successfully.', 'success')
plant = Plant.query.filter_by(
uuid=str(uuid_val),
owner_id=current_user.id
).first_or_404()
file = request.files.get('image')
if not file or file.filename == '':
flash('No file selected.', 'danger')
return redirect(url_for('plant.edit', uuid_val=plant.uuid))
try:
media = save_media_file(file, 'plants', plant.id)
media.uploader_id = current_user.id
db.session.add(media)
db.session.commit()
flash('Image uploaded.', 'success')
except Exception as e:
current_app.logger.error(f"Upload failed: {e}")
flash('Failed to upload image.', 'danger')
return redirect(url_for('plant.edit', uuid_val=plant.uuid))
@bp.route("/feature/<int:media_id>", methods=["POST"])
@login_required
def set_featured_image(media_id):
media = Media.query.get_or_404(media_id)
if current_user.id != media.uploader_id and current_user.role != "admin":
return jsonify({"error": "Not authorized"}), 403
plant = media.plant
plant.featured_media_id = media.id
db.session.commit()
return jsonify({"status": "success", "media_id": media.id})
@bp.route('/<uuid:uuid_val>/delete/<int:media_id>', methods=['POST'])
@login_required
@ -247,6 +298,7 @@ def delete_image(uuid_val, media_id):
flash('Image deleted.', 'success')
return redirect(url_for('plant.edit', uuid_val=plant.uuid))
@bp.route('/<uuid:uuid_val>/rotate/<int:media_id>', methods=['POST'])
@login_required
def rotate_image(uuid_val, media_id):
@ -255,3 +307,17 @@ def rotate_image(uuid_val, media_id):
rotate_media_file(media)
flash('Image rotated.', 'success')
return redirect(url_for('plant.edit', uuid_val=plant.uuid))
@bp.route('/f/<string:short_id>')
@bp.route('/<string:short_id>')
def view_card(short_id):
p = Plant.query.filter_by(short_id=short_id).first_or_404()
# 2) owner → straight to the normal detail page
if current_user.is_authenticated and p.owner_id == current_user.id:
return redirect(url_for('plant.detail', uuid_val=p.uuid))
# 3) everyone else → public card
featured = next((m for m in p.media_items if getattr(m, 'featured', False)), None)
return render_template('plant/card.html', plant=p, featured=featured)

View File

@ -0,0 +1,144 @@
{% extends 'core_ui/base.html' %}
{% block content %}
<div class="card mb-4">
<div class="card-body">
<h2 class="card-title">{{ plant.common_name.name }}</h2>
<h5 class="card-subtitle mb-3 text-muted">
{{ plant.scientific_name.name }}
</h5>
{# ── DESKTOP / TABLET GALLERY ──────────────────────────── #}
<div class="d-none d-md-block">
{# hero image #}
{% set hero = featured or plant.media_items|first %}
{% if hero %}
<div class="text-center mb-4">
<img
id="main-image"
src="{{ generate_image_url(hero) }}"
class="img-fluid"
style="max-height:60vh; object-fit:contain;"
alt="Image for {{ plant.common_name.name }}"
>
</div>
{% endif %}
{# thumbnails #}
<div class="d-flex flex-wrap justify-content-center gap-2 mb-3">
{% for m in plant.media_items %}
<img
src="{{ generate_image_url(m) }}"
class="img-thumbnail thumb{% if hero and m.id==hero.id %} active{% endif %}"
data-url="{{ generate_image_url(m) }}"
style="width:clamp(80px,15vw,120px); aspect-ratio:1/1; object-fit:cover; cursor:pointer;"
alt="Thumbnail"
>
{% endfor %}
</div>
</div>
{# ── MOBILE GRID GALLERY ─────────────────────────────── #}
<div class="d-block d-md-none">
<div class="row row-cols-3 g-2">
{% for m in plant.media_items %}
<div class="col">
<img
src="{{ generate_image_url(m) }}"
class="img-fluid mobile-thumb"
data-url="{{ generate_image_url(m) }}"
alt="Image for {{ plant.common_name.name }}"
style="aspect-ratio:1/1; object-fit:cover; cursor:pointer;"
>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
{# ── LIGHTBOX OVERLAY ─────────────────────────────────── #}
<div id="lightbox-overlay" class="d-none">
<span class="lightbox-close">&times;</span>
<img id="lightbox-image" src="" alt="Zoomed image">
</div>
<script>
(function(){
// Desktop thumbnail swapping
document.querySelectorAll('.thumb').forEach(thumb => {
thumb.addEventListener('click', () => {
const main = document.getElementById('main-image');
main.src = thumb.dataset.url;
document.querySelectorAll('.thumb.active')
.forEach(el => el.classList.remove('active'));
thumb.classList.add('active');
});
});
// Lightbox logic for mobile
const overlay = document.getElementById('lightbox-overlay');
const lbImage = document.getElementById('lightbox-image');
const closeBtn = document.querySelector('.lightbox-close');
document.querySelectorAll('.mobile-thumb').forEach(img => {
img.addEventListener('click', () => {
lbImage.src = img.dataset.url;
overlay.classList.remove('d-none');
});
});
// close handlers
closeBtn.addEventListener('click', () => {
overlay.classList.add('d-none');
lbImage.src = '';
});
overlay.addEventListener('click', e => {
if (e.target === overlay) {
overlay.classList.add('d-none');
lbImage.src = '';
}
});
// toggle zoom on lightbox image
lbImage.addEventListener('click', () => {
lbImage.classList.toggle('zoomed');
});
})();
</script>
<style>
/* Lightbox backdrop */
#lightbox-overlay {
position: fixed;
top:0; left:0; width:100vw; height:100vh;
background: rgba(0,0,0,0.8);
display: flex;
align-items: center;
justify-content: center;
z-index: 1050;
}
#lightbox-overlay.d-none { display: none; }
/* Zoomable image */
#lightbox-image {
max-width: 90%;
max-height: 90%;
cursor: zoom-in;
transition: transform 0.3s ease;
}
#lightbox-image.zoomed {
transform: scale(2);
cursor: zoom-out;
}
/* Close “X” */
.lightbox-close {
position: absolute;
top: 1rem; right: 1rem;
font-size: 2rem;
color: white;
cursor: pointer;
z-index: 1060;
}
</style>
{% endblock %}

View File

@ -1,71 +1,176 @@
{% extends 'core_ui/base.html' %}
{% block title %}
{{ plant.common_name.name if plant.common_name else "Unnamed Plant" }} Nature In Pots
{% endblock %}
{% block content %}
<div class="container my-4">
<div class="row gx-4">
<div class="col-md-4">
{% set featured = plant.featured_media or plant.media|first %}
<img
src="{{ generate_image_url(featured) }}"
alt="Image of {{ plant.common_name.name if plant.common_name else 'Plant' }}"
class="img-fluid rounded shadow-sm"
style="object-fit: cover; width: 100%; height: auto;"
>
</div>
<!-- Prev/Next Navigation -->
<div class="d-flex justify-content-between mb-3">
{% if prev_uuid %}
<a href="{{ url_for('plant.detail', uuid_val=prev_uuid) }}" class="btn btn-outline-primary">&larr; Previous</a>
{% else %}
<div></div>
{% endif %}
{% if next_uuid %}
<a href="{{ url_for('plant.detail', uuid_val=next_uuid) }}" class="btn btn-outline-primary">Next &rarr;</a>
{% else %}
<div></div>
{% endif %}
</div>
<div class="col-md-8">
<h2>
<div class="card mb-4">
<div class="card-header d-flex justify-content-between align-items-center">
<h2 class="mb-0">
{{ plant.common_name.name if plant.common_name else "Unnamed Plant" }}
<small class="text-muted">({{ plant.uuid }})</small>
</h2>
{% if plant.scientific_name %}
<h5 class="text-muted">
{{ plant.scientific_name.name }}
</h5>
{% if current_user.id == plant.owner_id %}
<a href="{{ url_for('plant.edit', uuid_val=plant.uuid) }}"
class="btn btn-sm btn-outline-secondary">Edit</a>
{% endif %}
</div>
<div class="card-body">
<dl class="row">
<dt class="col-sm-3">Type</dt>
<dd class="col-sm-9">{{ plant.plant_type }}</dd>
<p class="mt-3">
{{ plant.notes or "No description provided." }}
</p>
<dt class="col-sm-3">Scientific Name</dt>
<dd class="col-sm-9">{{ plant.scientific_name.name }}</dd>
{% if plant.mother_uuid %}
<p class="text-muted">
Parent:
<a href="{{ url_for('plant.detail', uuid_val=plant.mother_uuid) }}">
{{ plant.mother_uuid }}
</a>
</p>
{% endif %}
<dt class="col-sm-3">Mother UUID</dt>
<dd class="col-sm-9">
{% if plant.mother_uuid %}
<a href="{{ url_for('plant.detail', uuid_val=plant.mother_uuid) }}">
{{ plant.mother_uuid }}
</a>
{% else %}
N/A
{% endif %}
</dd>
<div class="mt-4">
<a
href="{{ url_for('plant.edit', uuid_val=plant.uuid) }}"
class="btn btn-primary me-2"
>Edit</a>
<a
href="{{ url_for('plant.index') }}"
class="btn btn-secondary"
>Back to List</a>
<dt class="col-sm-3">Notes</dt>
<dd class="col-sm-9">{{ plant.notes or '—' }}</dd>
</dl>
<div class="mb-3">
<a href="{{ url_for('utility.download_qr', uuid_val=plant.uuid) }}"
class="btn btn-primary me-1">Direct QR</a>
<a href="{{ url_for('utility.download_qr_card', uuid_val=plant.uuid) }}"
class="btn btn-secondary">Card QR</a>
</div>
{% if plant.media %}
<h5>Images</h5>
<div class="row g-2">
{% for m in plant.media %}
<div class="col-6 col-md-3">
<a href="{{ generate_image_url(m) }}" target="_blank" rel="noopener">
<img
src="{{ generate_image_url(m) }}"
class="img-fluid"
style="width:100%; height:150px; object-fit:cover;"
alt="{{ m.filename }}"
>
</a>
</div>
{% endfor %}
</div>
{% else %}
<p class="text-muted">No images uploaded yet.</p>
{% endif %}
{% if current_user.id == plant.owner_id %}
<hr>
<h5>Generate Cuttings</h5>
<form
method="POST"
action="{{ url_for('plant.generate_children', uuid_val=plant.uuid) }}"
class="row g-2 align-items-end"
>
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<div class="col-auto">
<label for="count" class="form-label">Number to generate</label>
<input
type="number"
id="count"
name="count"
class="form-control"
value="1"
min="1" max="100"
>
</div>
<div class="col-auto">
<button type="submit" class="btn btn-success">Generate</button>
</div>
</form>
{% if children %}
<hr>
<h5>Child Plants</h5>
{% if children|length > 6 %}
<ul class="list-group">
{% for c in children %}
<li class="list-group-item d-flex justify-content-between align-items-center">
<a href="{{ url_for('plant.detail', uuid_val=c.uuid) }}">
{{ c.common_name.name }} <small class="text-muted">({{ c.uuid }})</small>
</a>
<div>
<a href="{{ url_for('utility.download_qr', uuid_val=c.uuid) }}"
class="btn btn-sm btn-outline-primary me-1">Direct QR</a>
<a href="{{ url_for('utility.download_qr_card', uuid_val=c.uuid) }}"
class="btn btn-sm btn-outline-secondary">Card QR</a>
</div>
</li>
{% endfor %}
</ul>
{% else %}
<div class="row g-3">
{% for c in children %}
<div class="col-12 col-md-6">
<div class="card h-100">
<div class="d-flex justify-content-center align-items-center p-3">
{% if c.media %}
{% set first_media = c.media[0] %}
<a href="{{ generate_image_url(first_media) }}"
target="_blank" rel="noopener">
<img
src="{{ generate_image_url(first_media) }}"
style="width:150px; height:150px; object-fit:cover;"
alt="{{ first_media.filename }}"
>
</a>
{% else %}
<div style="width:150px; height:150px; background:#f0f0f0;"></div>
{% endif %}
</div>
<div class="card-body text-center">
<h6 class="card-title">
<a href="{{ url_for('plant.detail', uuid_val=c.uuid) }}">
{{ c.common_name.name }}
</a>
</h6>
<p class="card-subtitle mb-2 text-muted">
<a href="{{ url_for('plant.detail', uuid_val=c.uuid) }}">
{{ c.uuid }}
</a>
</p>
</div>
<div class="card-footer text-center">
<a href="{{ url_for('utility.download_qr', uuid_val=c.uuid) }}"
class="btn btn-sm btn-outline-primary me-1">Direct QR</a>
<a href="{{ url_for('utility.download_qr_card', uuid_val=c.uuid) }}"
class="btn btn-sm btn-outline-secondary">Card QR</a>
</div>
</div>
</div>
{% endfor %}
</div>
{% endif %}
{% endif %}
{% endif %}
</div>
</div>
{% if plant.media|length > (1 if plant.featured_media else 0) %}
<hr class="my-4">
<h4>Additional Images</h4>
<div class="d-flex flex-wrap gap-3">
{% for img in plant.media if img != featured %}
<img
src="{{ generate_image_url(img) }}"
alt="Plant image"
class="img-thumbnail"
style="height: 160px; object-fit: cover;"
>
{% endfor %}
</div>
{% endif %}
</div>
<a href="{{ url_for('plant.index') }}" class="btn btn-link">&larr; Back to list</a>
{% endblock %}

View File

@ -72,10 +72,12 @@
{# ——— Existing Images & Featured Toggle ——— #}
<h4>Existing Images</h4>
<form method="POST"
id="delete-images-form"
action="{{ url_for('media.bulk_delete_media', plant_uuid=plant.uuid) }}"
onsubmit="return confirm('Are you sure you want to delete selected images?');">
<form
method="POST"
id="delete-images-form"
action="{{ url_for('media.bulk_delete_media', plant_uuid=plant.uuid) }}"
onsubmit="return confirm('Are you sure you want to delete selected images?');"
>
{{ form.csrf_token }}
<div class="row">
{% for media in plant.media_items %}
@ -84,32 +86,43 @@
<img
id="image-{{ media.id }}"
src="{{ url_for('media.media_file',
context='plants',
context_id=plant.id,
filename=media.filename) }}"
context='plants',
context_id=plant.id,
filename=media.filename) }}"
class="card-img-top img-fluid"
alt="Plant Image"
style="object-fit:cover; height:150px;"
>
<div class="card-body text-center">
{# Featured radio driven off media.featured #}
<div class="form-check mb-2">
{# — featured toggle — #}
<form
action="{{ url_for('media.set_featured_image',
context='plants',
context_id=plant.id,
media_id=media.id) }}"
method="post"
class="d-inline"
>
<input
class="form-check-input featured-radio"
type="radio"
name="featured_media"
value="{{ media.id }}"
{% if media.featured %}checked{% endif %}
data-url="{{ url_for('media.set_featured_image',
context='plants',
context_id=plant.id,
media_id=media.id) }}"
type="hidden"
name="csrf_token"
value="{{ form.csrf_token._value() }}"
>
<label class="form-check-label">Featured</label>
</div>
<div class="form-check mb-2">
<input
class="form-check-input"
type="radio"
name="featured_media"
value="{{ media.id }}"
{% if media.featured %}checked{% endif %}
onchange="this.form.submit()"
>
<label class="form-check-label">Featured</label>
</div>
</form>
{# Rotate button #}
{# — rotate button #}
<button
type="button"
class="btn btn-outline-secondary btn-sm rotate-btn"
@ -117,66 +130,44 @@
data-id="{{ media.id }}"
>Rotate</button>
{# Delete checkbox #}
{# — delete checkbox #}
<div class="form-check mt-2">
<input
class="form-check-input delete-checkbox"
type="checkbox"
name="delete_ids"
value="{{ media.id }}"
id="del-{{ media.id }}"
>
<label class="form-check-label">Delete</label>
<label class="form-check-label" for="del-{{ media.id }}">Delete</label>
</div>
</div>
</div>
</div>
{% else %}
<p class="text-muted">No images uploaded yet.</p>
{% endfor %}
</div>
<button type="submit" class="btn btn-danger mt-2">Delete Selected Images</button>
</form>
</div>
{% endblock %}
{% block scripts %}
{{ super() }}
<script>
const csrfToken = "{{ form.csrf_token._value() }}";
<script>
const csrfToken = "{{ form.csrf_token._value() }}";
// Rotate buttons
document.querySelectorAll('.rotate-btn').forEach(btn => {
btn.addEventListener('click', () => {
fetch(btn.dataset.url, {
method: 'POST',
headers: { 'X-CSRFToken': csrfToken }
})
.then(r => {
if (!r.ok) throw Error();
const img = document.getElementById(`image-${btn.dataset.id}`);
img.src = img.src.split('?')[0] + `?v=${Date.now()}`;
})
.catch(() => alert('Failed to rotate image.'));
});
// Rotate buttons
document.querySelectorAll('.rotate-btn').forEach(btn => {
btn.addEventListener('click', () => {
fetch(btn.dataset.url, {
method: 'POST',
headers: { 'X-CSRFToken': csrfToken }
})
.then(r => {
if (!r.ok) throw Error();
const img = document.getElementById(`image-${btn.dataset.id}`);
img.src = img.src.split('?')[0] + `?v=${Date.now()}`;
})
.catch(() => alert('Failed to rotate image.'));
});
// Featuredradio AJAX
document.querySelectorAll('.featured-radio').forEach(radio => {
radio.addEventListener('change', () => {
fetch(radio.dataset.url, {
method: 'POST',
headers: { 'X-CSRFToken': csrfToken }
})
.then(r => {
if (!r.ok) throw Error();
// uncheck them all, then check this one
document.querySelectorAll('.featured-radio')
.forEach(r => r.checked = false);
radio.checked = true;
})
.catch(() => alert('Could not set featured image.'));
});
});
</script>
});
</script>
{% endblock %}

View File

@ -148,17 +148,13 @@
data-name="{{ plant.common_name.name|lower }}"
data-type="{{ plant.plant_type|lower }}">
<div class="card h-100">
{% set featured = plant.featured_media %}
{# Determine featured image: first any marked featured, else first media #}
{% set featured = plant.media|selectattr('featured')|first %}
{% if not featured and plant.media %}
{% set featured = plant.media[0] %}
{% endif %}
<a href="{{ url_for('plant.detail', uuid_val=plant.uuid) }}">
{# pick featured → first media if no explicit featured #}
{% set featured = plant.featured_media %}
{% if not featured and plant.media %}
{% set featured = plant.media[0] %}
{% endif %}
<img
src="{{ generate_image_url(featured) }}"
class="card-img-top"