sections!

This commit is contained in:
2025-06-08 17:07:31 +02:00
parent b616369b6f
commit 3a4e7bf41b
23 changed files with 322 additions and 48 deletions

142
app.py
View File

@@ -53,6 +53,15 @@ class Product(db.Model):
def __repr__(self):
return f"Product('{self.name}')"
class Section(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False, unique=True)
description = db.Column(db.Text, nullable=True)
icon = db.Column(db.String(200), nullable=True)
def __repr__(self):
return f"Section('{self.name}')"
class Plant(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
@@ -64,6 +73,7 @@ class Plant(db.Model):
size_id = db.Column(db.Integer, db.ForeignKey('size.id'), nullable=True)
care_difficulty_id = db.Column(db.Integer, db.ForeignKey('care_difficulty.id'), nullable=True)
growth_rate_id = db.Column(db.Integer, db.ForeignKey('growth_rate.id'), nullable=True)
section_id = db.Column(db.Integer, db.ForeignKey('section.id'), nullable=True)
products = db.Column(db.Text, nullable=True) # Will store product IDs as comma-separated values
description = db.Column(db.Text, nullable=True)
date_added = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
@@ -76,6 +86,7 @@ class Plant(db.Model):
size = db.relationship('Size', backref='plant_size')
care_difficulty = db.relationship('CareDifficulty', backref='plant_care_difficulty')
growth_rate = db.relationship('GrowthRate', backref='plant_growth_rate')
section = db.relationship('Section', backref='plants')
def __repr__(self):
return f"Plant('{self.name}', '{self.date_added}')"
@@ -140,13 +151,15 @@ def inject_admin_counts():
climate_count = Climate.query.count()
product_count = Product.query.count()
plant_count = Plant.query.count()
section_count = Section.query.count()
except Exception:
environment_count = climate_count = product_count = plant_count = 0
environment_count = climate_count = product_count = plant_count = section_count = 0
return dict(
environment_count=environment_count,
climate_count=climate_count,
product_count=product_count,
plant_count=plant_count
plant_count=plant_count,
section_count=section_count
)
def none_if_empty(val):
@@ -1126,6 +1139,91 @@ def delete_growth_rate(rate_id):
flash('Growth rate category deleted successfully!', 'success')
return redirect(url_for('manage_growth_rates'))
# Section management routes
@app.route('/admin/sections', methods=['GET', 'POST'])
def manage_sections():
if not is_logged_in():
return redirect(url_for('login'))
if request.method == 'POST':
name = request.form['name']
description = request.form['description']
icon_file = request.files.get('icon')
icon_filename = None
if not name:
flash('Name is required!', 'danger')
print('No name provided')
return redirect(url_for('manage_sections'))
if Section.query.filter_by(name=name).first():
flash('Section with this name already exists!', 'danger')
print('Duplicate section name')
return redirect(url_for('manage_sections'))
if icon_file and icon_file.filename:
icon_filename = secure_filename(icon_file.filename)
icon_path = os.path.join('static/icons', icon_filename)
os.makedirs('static/icons', exist_ok=True)
try:
icon_file.save(icon_path)
except Exception as e:
print('Error saving icon:', e)
flash(f'Error saving icon: {e}', 'danger')
try:
section = Section(name=name, description=description, icon=icon_filename)
db.session.add(section)
db.session.commit()
flash('Section added successfully!', 'success')
print('Section added:', name)
except Exception as e:
db.session.rollback()
print('Error adding section:', e)
flash(f'Error adding section: {e}', 'danger')
return redirect(url_for('manage_sections'))
sections = Section.query.all()
return render_template('manage_sections.html',
sections=sections,
plant_count=len(Plant.query.all()),
climate_count=len(Climate.query.all()),
environment_count=len(Environment.query.all()),
product_count=len(Product.query.all()),
light_count=len(Light.query.all()),
toxicity_count=len(Toxicity.query.all()),
size_count=len(Size.query.all()),
difficulty_count=len(CareDifficulty.query.all()),
rate_count=len(GrowthRate.query.all()),
section_count=len(sections))
@app.route('/admin/sections/edit/<int:section_id>', methods=['GET', 'POST'])
def edit_section(section_id):
if not is_logged_in():
return redirect(url_for('login'))
section = Section.query.get_or_404(section_id)
if request.method == 'POST':
section.name = request.form['name']
section.description = request.form['description']
icon_file = request.files.get('icon')
if icon_file and icon_file.filename:
icon_filename = secure_filename(icon_file.filename)
icon_path = os.path.join('static/icons', icon_filename)
os.makedirs('static/icons', exist_ok=True)
try:
icon_file.save(icon_path)
except Exception as e:
print('Error saving icon:', e)
section.icon = icon_filename
db.session.commit()
flash('Section updated successfully!', 'success')
return redirect(url_for('manage_sections'))
return render_template('edit_section.html', section=section)
@app.route('/admin/sections/delete/<int:section_id>', methods=['POST'])
def delete_section(section_id):
if not is_logged_in():
return redirect(url_for('login'))
section = Section.query.get_or_404(section_id)
db.session.delete(section)
db.session.commit()
flash('Section deleted successfully!', 'success')
return redirect(url_for('manage_sections'))
def seed_db():
# Environments
environments = [
@@ -1137,6 +1235,18 @@ def seed_db():
if not Environment.query.filter_by(name=env['name']).first():
db.session.add(Environment(name=env['name'], description=env['description']))
# Sections
sections = [
{'name': 'Succulents', 'description': 'Plants that store water in their leaves, stems, or roots.'},
{'name': 'Tropical', 'description': 'Plants native to tropical regions.'},
{'name': 'Herbs', 'description': 'Plants used for culinary, medicinal, or aromatic purposes.'},
{'name': 'Flowering', 'description': 'Plants grown primarily for their flowers.'},
{'name': 'Foliage', 'description': 'Plants grown primarily for their attractive leaves.'}
]
for sec in sections:
if not Section.query.filter_by(name=sec['name']).first():
db.session.add(Section(name=sec['name'], description=sec['description']))
# Climates
climates = [
{'name': 'Tropical', 'description': 'Warm and humid year-round.'},
@@ -1233,57 +1343,64 @@ def seed_db():
medium = Size.query.filter_by(name='Medium').first()
easy = CareDifficulty.query.filter_by(name='Easy').first()
moderate = GrowthRate.query.filter_by(name='Moderate').first()
# Get section instances
succulents = Section.query.filter_by(name='Succulents').first()
tropical_section = Section.query.filter_by(name='Tropical').first()
herbs = Section.query.filter_by(name='Herbs').first()
flowering = Section.query.filter_by(name='Flowering').first()
foliage = Section.query.filter_by(name='Foliage').first()
# 10 example plants
seed_plants = [
dict(name='Monstera Deliciosa', climate=tropical, environment=indoor,
light=bright_indirect, toxicity=non_toxic, size=medium,
care_difficulty=easy, growth_rate=moderate,
care_difficulty=easy, growth_rate=moderate, section=tropical_section,
products=[soil, fert], description='A popular tropical houseplant with large, split leaves.',
care_guide='<ul><li>Water when the top 2 inches of soil are dry.</li><li>Provide bright, indirect light.</li><li>Fertilize monthly during growing season.</li></ul>'),
dict(name='Aloe Vera', climate=arid, environment=indoor,
light=bright_indirect, toxicity=non_toxic, size=medium,
care_difficulty=easy, growth_rate=moderate,
care_difficulty=easy, growth_rate=moderate, section=succulents,
products=[soil], description='A succulent known for its medicinal properties.',
care_guide='<ul><li>Allow soil to dry completely between waterings.</li><li>Place in bright, indirect sunlight.</li><li>Use well-draining soil.</li></ul>'),
dict(name='Fiddle Leaf Fig', climate=tropical, environment=indoor,
light=bright_indirect, toxicity=non_toxic, size=medium,
care_difficulty=moderate, growth_rate=moderate,
care_difficulty=moderate, growth_rate=moderate, section=foliage,
products=[soil, fert, can], description='A trendy houseplant with large, violin-shaped leaves.',
care_guide='<ul><li>Keep soil consistently moist but not soggy.</li><li>Needs bright, filtered light.</li><li>Rotate plant for even growth.</li></ul>'),
dict(name='Snake Plant', climate=arid, environment=indoor,
light=bright_indirect, toxicity=non_toxic, size=medium,
care_difficulty=easy, growth_rate=moderate,
care_difficulty=easy, growth_rate=moderate, section=foliage,
products=[soil, can], description='A hardy plant that tolerates low light and irregular watering.',
care_guide='<ul><li>Water sparingly; let soil dry out between waterings.</li><li>Tolerates low to bright light.</li><li>Wipe leaves to remove dust.</li></ul>'),
dict(name='Spider Plant', climate=temperate, environment=indoor,
light=bright_indirect, toxicity=non_toxic, size=medium,
care_difficulty=easy, growth_rate=moderate,
care_difficulty=easy, growth_rate=moderate, section=foliage,
products=[soil, can], description='An easy-care plant with arching leaves and baby plantlets.',
care_guide='<ul><li>Keep soil slightly moist.</li><li>Thrives in bright, indirect light.</li><li>Trim brown tips as needed.</li></ul>'),
dict(name='Peace Lily', climate=tropical, environment=indoor,
light=bright_indirect, toxicity=non_toxic, size=medium,
care_difficulty=easy, growth_rate=moderate,
care_difficulty=easy, growth_rate=moderate, section=flowering,
products=[soil, fert, can], description='A flowering plant that thrives in shade and purifies air.',
care_guide='<ul><li>Water when leaves droop slightly.</li><li>Prefers low to medium light.</li><li>Remove spent flowers to encourage new blooms.</li></ul>'),
dict(name='Jade Plant', climate=arid, environment=indoor,
light=bright_indirect, toxicity=non_toxic, size=medium,
care_difficulty=easy, growth_rate=moderate,
care_difficulty=easy, growth_rate=moderate, section=succulents,
products=[soil], description='A succulent with thick, shiny leaves and a tree-like form.',
care_guide='<ul><li>Let soil dry between waterings.</li><li>Needs several hours of direct sunlight.</li><li>Prune to maintain shape.</li></ul>'),
dict(name='Tomato', climate=temperate, environment=outdoor,
light=bright_indirect, toxicity=non_toxic, size=medium,
care_difficulty=moderate, growth_rate=moderate,
care_difficulty=moderate, growth_rate=moderate, section=herbs,
products=[soil, fert, can], description='A classic edible plant for outdoor gardens.',
care_guide='<ul><li>Water regularly, keeping soil consistently moist.</li><li>Provide full sun.</li><li>Support with stakes or cages.</li></ul>'),
dict(name='Basil', climate=mediterranean, environment=greenhouse,
light=bright_indirect, toxicity=non_toxic, size=medium,
care_difficulty=easy, growth_rate=moderate,
care_difficulty=easy, growth_rate=moderate, section=herbs,
products=[soil, fert, light], description='A fragrant herb often grown in greenhouses or sunny windows.',
care_guide='<ul><li>Water when soil surface is dry.</li><li>Needs at least 6 hours of sunlight daily.</li><li>Pinch off flowers to encourage leaf growth.</li></ul>'),
dict(name='Cactus', climate=arid, environment=indoor,
light=bright_indirect, toxicity=non_toxic, size=medium,
care_difficulty=easy, growth_rate=moderate,
care_difficulty=easy, growth_rate=moderate, section=succulents,
products=[soil, light], description='A spiny plant adapted to dry, sunny conditions.',
care_guide='<ul><li>Water sparingly, especially in winter.</li><li>Place in bright, direct sunlight.</li><li>Use cactus-specific soil mix.</li></ul>'),
]
@@ -1297,6 +1414,7 @@ def seed_db():
size_id=plant['size'].id if plant['size'] else None,
care_difficulty_id=plant['care_difficulty'].id if plant['care_difficulty'] else None,
growth_rate_id=plant['growth_rate'].id if plant['growth_rate'] else None,
section_id=plant['section'].id if plant['section'] else None,
products=','.join(str(p.id) for p in plant['products'] if p),
description=plant['description'],
care_guide=plant['care_guide']