From 761cb180c503fee6f7679cb0dd5c4e8d455aef5b Mon Sep 17 00:00:00 2001 From: Joren de Graaf Date: Sat, 3 Oct 2026 20:41:45 +0200 Subject: [PATCH] adding food logging, phase 1 --- main/food/admin.py | 27 ++++ main/food/forms.py | 20 +++ main/food/migrations/0001_initial.py | 112 ++++++++++++++++ main/food/migrations/__init__.py | 0 main/food/models.py | 125 ++++++++++++++++++ main/food/services/__init__.py | 1 + main/food/templatetags/__init__.py | 1 + main/food/tests.py | 66 +++++++++ main/planner/forms.py | 18 +++ ...ersettings_carbohydrate_goal_g_and_more.py | 34 +++++ main/planner/models.py | 4 + .../templates/planner/user_settings.html | 1 + main/planner/views.py | 10 +- main/tasksnest/settings.py | 2 +- main/tasksnest/urls.py | 2 +- 15 files changed, 420 insertions(+), 3 deletions(-) create mode 100644 main/food/admin.py create mode 100644 main/food/forms.py create mode 100644 main/food/migrations/0001_initial.py create mode 100644 main/food/migrations/__init__.py create mode 100644 main/food/models.py create mode 100644 main/food/services/__init__.py create mode 100644 main/food/templatetags/__init__.py create mode 100644 main/food/tests.py create mode 100644 main/planner/migrations/0019_usersettings_carbohydrate_goal_g_and_more.py diff --git a/main/food/admin.py b/main/food/admin.py new file mode 100644 index 0000000..417fb96 --- /dev/null +++ b/main/food/admin.py @@ -0,0 +1,27 @@ +from django.contrib import admin + +from .models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct + + +@admin.register(FoodProduct) +class FoodProductAdmin(admin.ModelAdmin): + list_display = ('product_name', 'brand', 'barcode', 'source', 'owner', 'fetched_at') + list_filter = ('source', 'fetched_at') + search_fields = ('product_name', 'brand', 'barcode') + + +@admin.register(FoodLogEntry) +class FoodLogEntryAdmin(admin.ModelAdmin): + list_display = ('date', 'user', 'meal', 'product_name_snapshot', 'amount', 'unit', 'calories_kcal') + list_filter = ('date', 'meal', 'user') + search_fields = ('product_name_snapshot', 'brand_snapshot', 'barcode_snapshot') + + +@admin.register(FoodFavourite) +class FoodFavouriteAdmin(admin.ModelAdmin): + list_display = ('user', 'product', 'created_at') + + +@admin.register(FoodPortion) +class FoodPortionAdmin(admin.ModelAdmin): + list_display = ('user', 'product', 'label', 'amount', 'unit', 'is_default') diff --git a/main/food/forms.py b/main/food/forms.py new file mode 100644 index 0000000..69e4067 --- /dev/null +++ b/main/food/forms.py @@ -0,0 +1,20 @@ +from django import forms + +from .models import FoodProduct, Unit + + +class ManualFoodForm(forms.ModelForm): + class Meta: + model = FoodProduct + fields = ('product_name', 'brand', 'base_unit', 'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', 'fibre_100', 'sugars_100', 'salt_100') + labels = { + 'energy_kcal_100': 'Calories per 100 g or ml', + 'carbohydrates_100': 'Carbohydrates per 100 g or ml', + 'protein_100': 'Protein per 100 g or ml', + 'fat_100': 'Fat per 100 g or ml', + } + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + for field in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100'): + self.fields[field].required = True diff --git a/main/food/migrations/0001_initial.py b/main/food/migrations/0001_initial.py new file mode 100644 index 0000000..e013617 --- /dev/null +++ b/main/food/migrations/0001_initial.py @@ -0,0 +1,112 @@ +# Generated by Django 6.1.1 on 2026-10-03 18:39 + +import django.core.validators +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='FoodProduct', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('barcode', models.CharField(blank=True, db_index=True, max_length=64)), + ('product_name', models.CharField(max_length=255)), + ('brand', models.CharField(blank=True, max_length=255)), + ('image_url', models.URLField(blank=True)), + ('package_quantity', models.CharField(blank=True, max_length=100)), + ('serving_size_text', models.CharField(blank=True, max_length=100)), + ('serving_amount', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0.001)])), + ('serving_unit', models.CharField(blank=True, choices=[('g', 'g'), ('ml', 'ml')], max_length=2)), + ('base_unit', models.CharField(choices=[('g', 'g'), ('ml', 'ml')], default='g', max_length=2)), + ('energy_kcal_100', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('carbohydrates_100', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('protein_100', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('fat_100', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('saturated_fat_100', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('sugars_100', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('fibre_100', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('salt_100', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('source', models.CharField(choices=[('openfoodfacts', 'Open Food Facts'), ('manual', 'Manual')], default='manual', max_length=16)), + ('raw_data', models.JSONField(blank=True, default=dict)), + ('fetched_at', models.DateTimeField(blank=True, null=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='food_products', to=settings.AUTH_USER_MODEL)), + ], + ), + migrations.CreateModel( + name='FoodPortion', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('label', models.CharField(max_length=100)), + ('amount', models.DecimalField(decimal_places=3, max_digits=10, validators=[django.core.validators.MinValueValidator(0.001)])), + ('unit', models.CharField(choices=[('g', 'g'), ('ml', 'ml')], max_length=2)), + ('is_default', models.BooleanField(default=False)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='food_portions', to=settings.AUTH_USER_MODEL)), + ('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='portions', to='food.foodproduct')), + ], + ), + migrations.CreateModel( + name='FoodLogEntry', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('date', models.DateField(db_index=True)), + ('time', models.TimeField(blank=True, null=True)), + ('meal', models.CharField(choices=[('breakfast', 'Breakfast'), ('lunch', 'Lunch'), ('dinner', 'Dinner'), ('snacks', 'Snacks')], max_length=9)), + ('product_name_snapshot', models.CharField(max_length=255)), + ('brand_snapshot', models.CharField(blank=True, max_length=255)), + ('barcode_snapshot', models.CharField(blank=True, max_length=64)), + ('portion_label_snapshot', models.CharField(blank=True, max_length=100)), + ('amount', models.DecimalField(decimal_places=3, max_digits=10, validators=[django.core.validators.MinValueValidator(0.001)])), + ('unit', models.CharField(choices=[('g', 'g'), ('ml', 'ml')], max_length=2)), + ('calories_kcal', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('carbohydrates_g', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('protein_g', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('fat_g', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('fibre_g', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('sugars_g', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('salt_g', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])), + ('source', models.CharField(choices=[('openfoodfacts', 'Open Food Facts'), ('manual', 'Manual')], default='manual', max_length=16)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='food_log_entries', to=settings.AUTH_USER_MODEL)), + ('product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='log_entries', to='food.foodproduct')), + ], + options={ + 'ordering': ('date', 'time', 'pk'), + }, + ), + migrations.CreateModel( + name='FoodFavourite', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='food_favourites', to=settings.AUTH_USER_MODEL)), + ('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='favourites', to='food.foodproduct')), + ], + ), + migrations.AddConstraint( + model_name='foodproduct', + constraint=models.UniqueConstraint(condition=models.Q(('barcode', ''), _negated=True), fields=('owner', 'barcode'), name='food_unique_owner_barcode'), + ), + migrations.AddConstraint( + model_name='foodportion', + constraint=models.UniqueConstraint(fields=('user', 'product', 'label'), name='food_unique_portion_label'), + ), + migrations.AddConstraint( + model_name='foodfavourite', + constraint=models.UniqueConstraint(fields=('user', 'product'), name='food_unique_favourite'), + ), + ] diff --git a/main/food/migrations/__init__.py b/main/food/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/main/food/models.py b/main/food/models.py new file mode 100644 index 0000000..d05cd83 --- /dev/null +++ b/main/food/models.py @@ -0,0 +1,125 @@ +from django.conf import settings +from django.core.exceptions import ValidationError +from django.core.validators import MinValueValidator +from django.db import models +from django.db.models import Q + + +NON_NEGATIVE = [MinValueValidator(0)] +POSITIVE = [MinValueValidator(0.001)] + + +class Unit(models.TextChoices): + GRAM = 'g', 'g' + MILLILITRE = 'ml', 'ml' + + +class MealType(models.TextChoices): + BREAKFAST = 'breakfast', 'Breakfast' + LUNCH = 'lunch', 'Lunch' + DINNER = 'dinner', 'Dinner' + SNACKS = 'snacks', 'Snacks' + + +class FoodProduct(models.Model): + class Source(models.TextChoices): + OPEN_FOOD_FACTS = 'openfoodfacts', 'Open Food Facts' + MANUAL = 'manual', 'Manual' + + owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='food_products') + barcode = models.CharField(max_length=64, blank=True, db_index=True) + product_name = models.CharField(max_length=255) + brand = models.CharField(max_length=255, blank=True) + image_url = models.URLField(blank=True) + package_quantity = models.CharField(max_length=100, blank=True) + serving_size_text = models.CharField(max_length=100, blank=True) + serving_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE) + serving_unit = models.CharField(max_length=2, choices=Unit.choices, blank=True) + base_unit = models.CharField(max_length=2, choices=Unit.choices, default=Unit.GRAM) + energy_kcal_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) + carbohydrates_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) + protein_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) + fat_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) + saturated_fat_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) + sugars_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) + fibre_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) + salt_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) + source = models.CharField(max_length=16, choices=Source.choices, default=Source.MANUAL) + raw_data = models.JSONField(default=dict, blank=True) + fetched_at = models.DateTimeField(null=True, blank=True) + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + constraints = [models.UniqueConstraint(fields=('owner', 'barcode'), condition=~Q(barcode=''), name='food_unique_owner_barcode')] + + def __str__(self): + return self.product_name + + +class FoodLogEntry(models.Model): + user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='food_log_entries') + date = models.DateField(db_index=True) + time = models.TimeField(null=True, blank=True) + meal = models.CharField(max_length=9, choices=MealType.choices) + product = models.ForeignKey(FoodProduct, on_delete=models.SET_NULL, null=True, blank=True, related_name='log_entries') + product_name_snapshot = models.CharField(max_length=255) + brand_snapshot = models.CharField(max_length=255, blank=True) + barcode_snapshot = models.CharField(max_length=64, blank=True) + portion_label_snapshot = models.CharField(max_length=100, blank=True) + amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE) + unit = models.CharField(max_length=2, choices=Unit.choices) + calories_kcal = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) + carbohydrates_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) + protein_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) + fat_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) + fibre_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) + sugars_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) + salt_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) + source = models.CharField(max_length=16, choices=FoodProduct.Source.choices, default=FoodProduct.Source.MANUAL) + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + ordering = ('date', 'time', 'pk') + + def clean(self): + super().clean() + if self.product_id and self.user_id and self.product.owner_id != self.user_id: + raise ValidationError({'product': 'Choose one of your own food products.'}) + + def __str__(self): + return f'{self.product_name_snapshot} on {self.date}' + + +class FoodFavourite(models.Model): + user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='food_favourites') + product = models.ForeignKey(FoodProduct, on_delete=models.CASCADE, related_name='favourites') + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + constraints = [models.UniqueConstraint(fields=('user', 'product'), name='food_unique_favourite')] + + def clean(self): + super().clean() + if self.product_id and self.user_id and self.product.owner_id != self.user_id: + raise ValidationError({'product': 'Choose one of your own food products.'}) + + +class FoodPortion(models.Model): + user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='food_portions') + product = models.ForeignKey(FoodProduct, on_delete=models.CASCADE, related_name='portions') + label = models.CharField(max_length=100) + amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE) + unit = models.CharField(max_length=2, choices=Unit.choices) + is_default = models.BooleanField(default=False) + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + constraints = [models.UniqueConstraint(fields=('user', 'product', 'label'), name='food_unique_portion_label')] + + def clean(self): + super().clean() + if self.product_id and self.user_id and self.product.owner_id != self.user_id: + raise ValidationError({'product': 'Choose one of your own food products.'}) diff --git a/main/food/services/__init__.py b/main/food/services/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/main/food/services/__init__.py @@ -0,0 +1 @@ + diff --git a/main/food/templatetags/__init__.py b/main/food/templatetags/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/main/food/templatetags/__init__.py @@ -0,0 +1 @@ + diff --git a/main/food/tests.py b/main/food/tests.py new file mode 100644 index 0000000..37cad29 --- /dev/null +++ b/main/food/tests.py @@ -0,0 +1,66 @@ +from datetime import date +from decimal import Decimal + +from django.contrib.auth import get_user_model +from django.core.exceptions import ValidationError +from django.db import IntegrityError, transaction +from django.test import TestCase +from django.urls import reverse + +from .models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit + + +class FoodFoundationTests(TestCase): + def setUp(self): + self.user = get_user_model().objects.create_user(username='food-one', password='test-password') + self.other = get_user_model().objects.create_user(username='food-two', password='test-password') + self.product = FoodProduct.objects.create(owner=self.user, product_name='Yoghurt', barcode='123', base_unit=Unit.GRAM) + + def test_meals_are_fixed(self): + self.assertEqual(list(MealType.values), ['breakfast', 'lunch', 'dinner', 'snacks']) + + def test_missing_nutrients_remain_null(self): + self.product.refresh_from_db() + self.assertIsNone(self.product.energy_kcal_100) + self.assertIsNone(self.product.protein_100) + + def test_favourite_and_portion_uniqueness(self): + FoodFavourite.objects.create(user=self.user, product=self.product) + FoodPortion.objects.create(user=self.user, product=self.product, label='My bowl', amount=Decimal('300'), unit=Unit.GRAM) + with self.assertRaises(IntegrityError), transaction.atomic(): + FoodFavourite.objects.create(user=self.user, product=self.product) + with self.assertRaises(IntegrityError), transaction.atomic(): + FoodPortion.objects.create(user=self.user, product=self.product, label='My bowl', amount=Decimal('200'), unit=Unit.GRAM) + + def test_log_snapshot_survives_product_edit(self): + entry = FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.BREAKFAST, + product=self.product, product_name_snapshot='Yoghurt', amount=Decimal('300'), unit=Unit.GRAM, + calories_kcal=Decimal('174')) + self.product.product_name = 'Renamed yoghurt' + self.product.energy_kcal_100 = Decimal('100') + self.product.save() + entry.refresh_from_db() + self.assertEqual(entry.product_name_snapshot, 'Yoghurt') + self.assertEqual(entry.calories_kcal, Decimal('174')) + + def test_cross_user_product_reference_rejected(self): + for item in ( + FoodFavourite(user=self.other, product=self.product), + FoodPortion(user=self.other, product=self.product, label='Bowl', amount=Decimal('100'), unit=Unit.GRAM), + FoodLogEntry(user=self.other, product=self.product, date=date(2026, 10, 3), meal=MealType.LUNCH, + product_name_snapshot='Yoghurt', amount=Decimal('100'), unit=Unit.GRAM), + ): + with self.assertRaises(ValidationError): + item.full_clean() + + def test_food_route_requires_login(self): + self.assertEqual(self.client.get(reverse('food:diary')).status_code, 302) + self.client.force_login(self.user) + self.assertEqual(self.client.get(reverse('food:diary')).status_code, 200) + + def test_food_goals_reject_negative_values(self): + from planner.forms import FoodGoalForm + + form = FoodGoalForm(data={'daily_calorie_goal': '-1', 'carbohydrate_goal_g': '-1', + 'protein_goal_g': '10', 'fat_goal_g': '0'}) + self.assertFalse(form.is_valid()) diff --git a/main/planner/forms.py b/main/planner/forms.py index 5521d0f..e0af00d 100644 --- a/main/planner/forms.py +++ b/main/planner/forms.py @@ -169,6 +169,24 @@ class HydrationGoalForm(forms.ModelForm): widgets = {'daily_water_goal_ml': forms.NumberInput(attrs={'min': 250, 'max': 10000, 'step': 1})} +class FoodGoalForm(forms.ModelForm): + class Meta: + model = UserSettings + fields = ('daily_calorie_goal', 'carbohydrate_goal_g', 'protein_goal_g', 'fat_goal_g') + labels = { + 'daily_calorie_goal': 'Daily calorie goal (kcal)', + 'carbohydrate_goal_g': 'Daily carbohydrate target (g)', + 'protein_goal_g': 'Daily protein target (g)', + 'fat_goal_g': 'Daily fat target (g)', + } + widgets = { + 'daily_calorie_goal': forms.NumberInput(attrs={'min': 0, 'step': 1}), + 'carbohydrate_goal_g': forms.NumberInput(attrs={'min': 0, 'step': '0.1'}), + 'protein_goal_g': forms.NumberInput(attrs={'min': 0, 'step': '0.1'}), + 'fat_goal_g': forms.NumberInput(attrs={'min': 0, 'step': '0.1'}), + } + + class WaterIntakeForm(forms.Form): amount_ml = forms.IntegerField(min_value=1, max_value=3000) diff --git a/main/planner/migrations/0019_usersettings_carbohydrate_goal_g_and_more.py b/main/planner/migrations/0019_usersettings_carbohydrate_goal_g_and_more.py new file mode 100644 index 0000000..6adb8ba --- /dev/null +++ b/main/planner/migrations/0019_usersettings_carbohydrate_goal_g_and_more.py @@ -0,0 +1,34 @@ +# Generated by Django 6.1.1 on 2026-10-03 18:39 + +import django.core.validators +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('planner', '0018_fastingsettings_last_phase_notification_at'), + ] + + operations = [ + migrations.AddField( + model_name='usersettings', + name='carbohydrate_goal_g', + field=models.DecimalField(blank=True, decimal_places=1, max_digits=7, null=True, validators=[django.core.validators.MinValueValidator(0)]), + ), + migrations.AddField( + model_name='usersettings', + name='daily_calorie_goal', + field=models.PositiveIntegerField(blank=True, null=True), + ), + migrations.AddField( + model_name='usersettings', + name='fat_goal_g', + field=models.DecimalField(blank=True, decimal_places=1, max_digits=7, null=True, validators=[django.core.validators.MinValueValidator(0)]), + ), + migrations.AddField( + model_name='usersettings', + name='protein_goal_g', + field=models.DecimalField(blank=True, decimal_places=1, max_digits=7, null=True, validators=[django.core.validators.MinValueValidator(0)]), + ), + ] diff --git a/main/planner/models.py b/main/planner/models.py index 3e4b5b2..510b037 100644 --- a/main/planner/models.py +++ b/main/planner/models.py @@ -120,6 +120,10 @@ class UserSettings(models.Model): daily_water_goal_ml = models.PositiveIntegerField( default=2000, validators=[MinValueValidator(250), MaxValueValidator(10000)], ) + daily_calorie_goal = models.PositiveIntegerField(null=True, blank=True) + carbohydrate_goal_g = models.DecimalField(max_digits=7, decimal_places=1, null=True, blank=True, validators=[MinValueValidator(0)]) + protein_goal_g = models.DecimalField(max_digits=7, decimal_places=1, null=True, blank=True, validators=[MinValueValidator(0)]) + fat_goal_g = models.DecimalField(max_digits=7, decimal_places=1, null=True, blank=True, validators=[MinValueValidator(0)]) ntfy_url = models.URLField(blank=True) ntfy_enabled = models.BooleanField(default=False) ntfy_last_tested_at = models.DateTimeField(null=True, blank=True) diff --git a/main/planner/templates/planner/user_settings.html b/main/planner/templates/planner/user_settings.html index 0d5c131..44cc6b4 100644 --- a/main/planner/templates/planner/user_settings.html +++ b/main/planner/templates/planner/user_settings.html @@ -8,6 +8,7 @@

Location & weather

Location is optional and private. It is used only to retrieve your forecast.

{% csrf_token %}{% for field in profile_form %}
{{ field.label_tag }}{{ field }}{% if field.help_text %}{{ field.help_text }}{% endif %}{{ field.errors }}
{% endfor %}

Sick Day Mode

Temporarily defer routine work while you recover.

{% csrf_token %}{% for field in sick_form %}{% if field.name == 'enabled' %}
{{ field.errors }}
{% else %}
{{ field.label_tag }}{{ field }}{% if field.help_text %}{{ field.help_text }}{% endif %}{{ field.errors }}
{% endif %}{% endfor %}

Hydration

Set your daily water goal.

{% csrf_token %}{% for field in hydration_goal_form %}
{{ field.label_tag }}{{ field }}{{ field.errors }}
{% endfor %}
+

Food

Set optional daily nutrition goals. Exercise calories do not change these goals.

{% csrf_token %}{% for field in food_goal_form %}
{{ field.label_tag }}{{ field }}{{ field.errors }}
{% endfor %}

Notifications / ntfy

Enter your private topic URL, test it, then enable notifications.

diff --git a/main/planner/views.py b/main/planner/views.py index 0609566..f946b4a 100644 --- a/main/planner/views.py +++ b/main/planner/views.py @@ -19,7 +19,7 @@ from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import CreateView, DeleteView, DetailView, ListView, TemplateView, UpdateView from .forms import ( - DailyPlannerForm, FastingSettingsForm, RegistrationForm, SickDaySettingsForm, SleepCheckInForm, TimeZoneSettingsForm, + DailyPlannerForm, FastingSettingsForm, FoodGoalForm, RegistrationForm, SickDaySettingsForm, SleepCheckInForm, TimeZoneSettingsForm, BowelHealthCheckInForm, NeckHeadacheCheckInForm, TaskForm, UserSettingsForm, WorkoutForm, HydrationGoalForm, WaterIntakeForm, NtfySettingsForm, ) from .models import BowelHealthCheckIn, FastingPeriod, FastingSettings, NeckHeadacheCheckIn, SickDaySettings, SleepCheckIn, Task, ToothBrushing, UserSettings, Workout, WaterIntakeEntry @@ -753,6 +753,7 @@ def user_settings(request): fasting = FastingSettings.objects.filter(user=request.user).first() profile_form = UserSettingsForm(instance=profile) hydration_goal_form = HydrationGoalForm(instance=profile) + food_goal_form = FoodGoalForm(instance=profile) sick_form = SickDaySettingsForm(instance=sick_day) fasting_form = FastingSettingsForm(instance=fasting) time_zone_form = TimeZoneSettingsForm(instance=profile) @@ -772,6 +773,12 @@ def user_settings(request): hydration_goal_form.save() messages.success(request, 'Your daily water goal was saved.') return redirect('planner:user-settings') + elif section == 'food': + food_goal_form = FoodGoalForm(request.POST, instance=profile) + if food_goal_form.is_valid(): + food_goal_form.save() + messages.success(request, 'Your food goals were saved.') + return redirect('planner:user-settings') elif section == 'ntfy': old_url = profile.ntfy_url ntfy_form = NtfySettingsForm(request.POST, instance=profile) @@ -842,6 +849,7 @@ def user_settings(request): return render(request, 'planner/user_settings.html', { 'profile_form': profile_form, 'hydration_goal_form': hydration_goal_form, + 'food_goal_form': food_goal_form, 'sick_form': sick_form, 'fasting_form': fasting_form, 'time_zone_form': time_zone_form, diff --git a/main/tasksnest/settings.py b/main/tasksnest/settings.py index 76c53e0..1c35955 100644 --- a/main/tasksnest/settings.py +++ b/main/tasksnest/settings.py @@ -42,7 +42,7 @@ INSTALLED_APPS = [ 'django.contrib.messages', 'django.contrib.staticfiles', 'planner', - 'food', + 'food.apps.FoodConfig', ] MIDDLEWARE = [ diff --git a/main/tasksnest/urls.py b/main/tasksnest/urls.py index 8b8cdce..3c54b19 100644 --- a/main/tasksnest/urls.py +++ b/main/tasksnest/urls.py @@ -19,6 +19,6 @@ from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), - path('food/', include('food.urls')), + path('food/', include('food.urls', namespace='food')), path('', include('planner.urls')), ]