adding food logging, phase 1

This commit is contained in:
Joren de Graaf
2026-10-03 20:41:45 +02:00
parent 11ded97ed1
commit 761cb180c5
15 changed files with 420 additions and 3 deletions
+27
View File
@@ -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')
+20
View File
@@ -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
+112
View File
@@ -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'),
),
]
View File
+125
View File
@@ -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.'})
+1
View File
@@ -0,0 +1 @@
+1
View File
@@ -0,0 +1 @@
+66
View File
@@ -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())
+18
View File
@@ -169,6 +169,24 @@ class HydrationGoalForm(forms.ModelForm):
widgets = {'daily_water_goal_ml': forms.NumberInput(attrs={'min': 250, 'max': 10000, 'step': 1})} 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): class WaterIntakeForm(forms.Form):
amount_ml = forms.IntegerField(min_value=1, max_value=3000) amount_ml = forms.IntegerField(min_value=1, max_value=3000)
@@ -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)]),
),
]
+4
View File
@@ -120,6 +120,10 @@ class UserSettings(models.Model):
daily_water_goal_ml = models.PositiveIntegerField( daily_water_goal_ml = models.PositiveIntegerField(
default=2000, validators=[MinValueValidator(250), MaxValueValidator(10000)], 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_url = models.URLField(blank=True)
ntfy_enabled = models.BooleanField(default=False) ntfy_enabled = models.BooleanField(default=False)
ntfy_last_tested_at = models.DateTimeField(null=True, blank=True) ntfy_last_tested_at = models.DateTimeField(null=True, blank=True)
@@ -8,6 +8,7 @@
<section class="settings-card"><h2>Location &amp; weather</h2><p>Location is optional and private. It is used only to retrieve your forecast.</p><form method="post" data-geolocation-form>{% csrf_token %}<input type="hidden" name="section" value="location">{% for field in profile_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button button--secondary" type="button" data-use-location>Use my current location</button><span data-location-status role="status"></span><button class="button" type="submit">Save location</button></form></section> <section class="settings-card"><h2>Location &amp; weather</h2><p>Location is optional and private. It is used only to retrieve your forecast.</p><form method="post" data-geolocation-form>{% csrf_token %}<input type="hidden" name="section" value="location">{% for field in profile_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button button--secondary" type="button" data-use-location>Use my current location</button><span data-location-status role="status"></span><button class="button" type="submit">Save location</button></form></section>
<section class="settings-card"><h2>Sick Day Mode</h2><p>Temporarily defer routine work while you recover.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="sick-day">{% for field in sick_form %}{% if field.name == 'enabled' %}<div class="settings-switch-row"><label class="settings-switch"><span class="settings-switch__copy"><strong>Enable Sick Day Mode</strong><small>Give routine tasks a rest while you recover.</small></span>{{ field }}<span class="settings-switch__track" aria-hidden="true"></span></label>{{ field.errors }}</div>{% else %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endif %}{% endfor %}<button class="button" type="submit">Save Sick Day settings</button></form></section> <section class="settings-card"><h2>Sick Day Mode</h2><p>Temporarily defer routine work while you recover.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="sick-day">{% for field in sick_form %}{% if field.name == 'enabled' %}<div class="settings-switch-row"><label class="settings-switch"><span class="settings-switch__copy"><strong>Enable Sick Day Mode</strong><small>Give routine tasks a rest while you recover.</small></span>{{ field }}<span class="settings-switch__track" aria-hidden="true"></span></label>{{ field.errors }}</div>{% else %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endif %}{% endfor %}<button class="button" type="submit">Save Sick Day settings</button></form></section>
<section class="settings-card"><h2>Hydration</h2><p>Set your daily water goal.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="hydration">{% for field in hydration_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save water goal</button></form></section> <section class="settings-card"><h2>Hydration</h2><p>Set your daily water goal.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="hydration">{% for field in hydration_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save water goal</button></form></section>
<section class="settings-card"><h2>Food</h2><p>Set optional daily nutrition goals. Exercise calories do not change these goals.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="food">{% for field in food_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save food goals</button></form></section>
<section class="settings-card" aria-labelledby="ntfy-title"> <section class="settings-card" aria-labelledby="ntfy-title">
<h2 id="ntfy-title">Notifications / ntfy</h2> <h2 id="ntfy-title">Notifications / ntfy</h2>
<p>Enter your private topic URL, test it, then enable notifications.</p> <p>Enter your private topic URL, test it, then enable notifications.</p>
+9 -1
View File
@@ -19,7 +19,7 @@ from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import CreateView, DeleteView, DetailView, ListView, TemplateView, UpdateView from django.views.generic import CreateView, DeleteView, DetailView, ListView, TemplateView, UpdateView
from .forms import ( from .forms import (
DailyPlannerForm, FastingSettingsForm, RegistrationForm, SickDaySettingsForm, SleepCheckInForm, TimeZoneSettingsForm, DailyPlannerForm, FastingSettingsForm, FoodGoalForm, RegistrationForm, SickDaySettingsForm, SleepCheckInForm, TimeZoneSettingsForm,
BowelHealthCheckInForm, NeckHeadacheCheckInForm, TaskForm, UserSettingsForm, WorkoutForm, HydrationGoalForm, WaterIntakeForm, NtfySettingsForm, BowelHealthCheckInForm, NeckHeadacheCheckInForm, TaskForm, UserSettingsForm, WorkoutForm, HydrationGoalForm, WaterIntakeForm, NtfySettingsForm,
) )
from .models import BowelHealthCheckIn, FastingPeriod, FastingSettings, NeckHeadacheCheckIn, SickDaySettings, SleepCheckIn, Task, ToothBrushing, UserSettings, Workout, WaterIntakeEntry 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() fasting = FastingSettings.objects.filter(user=request.user).first()
profile_form = UserSettingsForm(instance=profile) profile_form = UserSettingsForm(instance=profile)
hydration_goal_form = HydrationGoalForm(instance=profile) hydration_goal_form = HydrationGoalForm(instance=profile)
food_goal_form = FoodGoalForm(instance=profile)
sick_form = SickDaySettingsForm(instance=sick_day) sick_form = SickDaySettingsForm(instance=sick_day)
fasting_form = FastingSettingsForm(instance=fasting) fasting_form = FastingSettingsForm(instance=fasting)
time_zone_form = TimeZoneSettingsForm(instance=profile) time_zone_form = TimeZoneSettingsForm(instance=profile)
@@ -772,6 +773,12 @@ def user_settings(request):
hydration_goal_form.save() hydration_goal_form.save()
messages.success(request, 'Your daily water goal was saved.') messages.success(request, 'Your daily water goal was saved.')
return redirect('planner:user-settings') 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': elif section == 'ntfy':
old_url = profile.ntfy_url old_url = profile.ntfy_url
ntfy_form = NtfySettingsForm(request.POST, instance=profile) ntfy_form = NtfySettingsForm(request.POST, instance=profile)
@@ -842,6 +849,7 @@ def user_settings(request):
return render(request, 'planner/user_settings.html', { return render(request, 'planner/user_settings.html', {
'profile_form': profile_form, 'profile_form': profile_form,
'hydration_goal_form': hydration_goal_form, 'hydration_goal_form': hydration_goal_form,
'food_goal_form': food_goal_form,
'sick_form': sick_form, 'sick_form': sick_form,
'fasting_form': fasting_form, 'fasting_form': fasting_form,
'time_zone_form': time_zone_form, 'time_zone_form': time_zone_form,
+1 -1
View File
@@ -42,7 +42,7 @@ INSTALLED_APPS = [
'django.contrib.messages', 'django.contrib.messages',
'django.contrib.staticfiles', 'django.contrib.staticfiles',
'planner', 'planner',
'food', 'food.apps.FoodConfig',
] ]
MIDDLEWARE = [ MIDDLEWARE = [
+1 -1
View File
@@ -19,6 +19,6 @@ from django.urls import include, path
urlpatterns = [ urlpatterns = [
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
path('food/', include('food.urls')), path('food/', include('food.urls', namespace='food')),
path('', include('planner.urls')), path('', include('planner.urls')),
] ]