Recipes phase 1

This commit is contained in:
Joren de Graaf
2026-10-12 01:37:51 +02:00
parent 000ec834b0
commit 500f72382a
19 changed files with 747 additions and 1 deletions
+2 -1
View File
@@ -24,6 +24,7 @@
<a id="daily-planner-nav" class="{% if onboarding_tour.target == 'daily-planner' %}onboarding-highlight{% endif %}" href="{% url 'planner:daily-planner' %}">Daily planner</a>
<a id="health-nav" class="{% if onboarding_tour.target == 'wellbeing' %}onboarding-highlight{% endif %}" href="{% url 'planner:health' %}">Health</a>
<a href="{% url 'food:diary' %}">Food</a>
<a href="{% url 'recipes:list' %}"{% if request.resolver_match.namespace == 'recipes' %} aria-current="page"{% endif %}>Recipes</a>
<a href="{% url 'food:inventory' %}">Kitchen Inventory</a>
<a id="settings-nav" class="{% if onboarding_tour.target == 'settings' %}onboarding-highlight{% endif %}" href="{% url 'planner:user-settings' %}">Settings</a>
<form method="post" action="{% url 'planner:user-settings' %}" class="theme-toggle">{% csrf_token %}<input type="hidden" name="section" value="appearance"><input type="hidden" name="next" value="{{ request.path }}">{% if user_appearance == 'dark' %}<input type="hidden" name="appearance" value="light"><button type="submit" aria-label="Use light mode" title="Use light mode"><span aria-hidden="true">☀</span><span class="sr-only">Use light mode</span></button>{% else %}<input type="hidden" name="appearance" value="dark"><button type="submit" aria-label="Use dark mode" title="Use dark mode"><span aria-hidden="true">☾</span><span class="sr-only">Use dark mode</span></button>{% endif %}</form>
@@ -36,7 +37,7 @@
</div>
</header>
<div class="mobile-nav-backdrop" data-nav-backdrop hidden></div>
<main class="page-content">
<main class="page-content {% block page_class %}{% endblock %}">
{% if messages %}{% for message in messages %}<p class="flash-message" role="status">{{ message }}</p>{% endfor %}{% endif %}
{% block content %}{% endblock %}
</main>
View File
+3
View File
@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.
+5
View File
@@ -0,0 +1,5 @@
from django.apps import AppConfig
class RecipesConfig(AppConfig):
name = 'recipes'
+96
View File
@@ -0,0 +1,96 @@
from django import forms
from django.forms import BaseInlineFormSet, inlineformset_factory
from django.core.files.uploadedfile import UploadedFile
from PIL import Image, UnidentifiedImageError
from food.models import FoodProduct
from .models import Recipe, RecipeIngredient
class RecipeForm(forms.ModelForm):
tags_text = forms.CharField(required=False, label='Tags',
help_text='Separate tags with commas.')
remove_photo = forms.BooleanField(required=False, label='Remove current photo')
class Meta:
model = Recipe
fields = ('title', 'description', 'category', 'preparation_minutes',
'cooking_minutes', 'default_servings', 'status', 'parent',
'instructions_markdown', 'notes_markdown', 'photo')
labels = {'instructions_markdown': 'Instructions (Markdown)',
'notes_markdown': 'Personal notes (Markdown)',
'default_servings': 'Servings', 'parent': 'Variation of'}
widgets = {
'description': forms.Textarea(attrs={'rows': 3}),
'instructions_markdown': forms.Textarea(attrs={'rows': 10}),
'notes_markdown': forms.Textarea(attrs={'rows': 4}),
'photo': forms.ClearableFileInput(attrs={'accept': 'image/jpeg,image/png,image/webp'}),
'preparation_minutes': forms.NumberInput(attrs={'min': 0}),
'cooking_minutes': forms.NumberInput(attrs={'min': 0}),
'default_servings': forms.NumberInput(attrs={'min': '.01', 'step': '.01'}),
}
def __init__(self, *args, user, **kwargs):
super().__init__(*args, **kwargs)
self.fields['parent'].queryset = Recipe.objects.filter(owner=user).exclude(pk=self.instance.pk)
if self.instance.pk:
self.fields['tags_text'].initial = ', '.join(self.instance.tags)
def clean_tags_text(self):
tags = [tag.strip() for tag in self.cleaned_data['tags_text'].split(',') if tag.strip()]
if len(tags) > 12 or any(len(tag) > 40 for tag in tags):
raise forms.ValidationError('Use up to 12 tags of at most 40 characters each.')
return list(dict.fromkeys(tags))
def clean_photo(self):
photo = self.cleaned_data.get('photo')
if not isinstance(photo, UploadedFile):
return photo
if photo.size > 5 * 1024 * 1024:
raise forms.ValidationError('Choose an image smaller than 5 MB.')
if photo.content_type not in ('image/jpeg', 'image/png', 'image/webp'):
raise forms.ValidationError('Choose a JPEG, PNG, or WebP image.')
try:
image = Image.open(photo)
if image.format not in ('JPEG', 'PNG', 'WEBP') or image.width * image.height > 25_000_000:
raise forms.ValidationError('Choose a valid image smaller than 25 megapixels.')
image.verify()
except (UnidentifiedImageError, OSError):
raise forms.ValidationError('Choose a valid JPEG, PNG, or WebP image.') from None
finally:
photo.seek(0)
return photo
def save(self, commit=True):
recipe = super().save(commit=False)
recipe.tags = self.cleaned_data['tags_text']
if commit:
recipe.save()
return recipe
class RecipeIngredientForm(forms.ModelForm):
class Meta:
model = RecipeIngredient
fields = ('name', 'quantity', 'unit', 'preparation_note', 'is_optional',
'inventory_product', 'nutrition_product', 'display_order')
widgets = {'quantity': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}),
'display_order': forms.NumberInput(attrs={'min': 0})}
class OwnedIngredientFormSet(BaseInlineFormSet):
def __init__(self, *args, user, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
def add_fields(self, form, index):
super().add_fields(form, index)
products = FoodProduct.objects.filter(owner=self.user).order_by('product_name')
for name in ('inventory_product', 'nutrition_product'):
form.fields[name].queryset = products
RecipeIngredientFormSet = inlineformset_factory(
Recipe, RecipeIngredient, form=RecipeIngredientForm,
formset=OwnedIngredientFormSet, extra=2, can_delete=True,
)
+108
View File
@@ -0,0 +1,108 @@
# Generated by Django 6.1.1 on 2026-10-11 18:51
import django.core.validators
import django.db.models.deletion
import uuid
from decimal import Decimal
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('food', '0009_backfill_food_hydration'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Recipe',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('api_id', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('title', models.CharField(max_length=180)),
('description', models.TextField(blank=True)),
('instructions_markdown', models.TextField(blank=True)),
('notes_markdown', models.TextField(blank=True)),
('photo', models.ImageField(blank=True, upload_to='recipes/%Y/%m/')),
('preparation_minutes', models.PositiveIntegerField(default=0)),
('cooking_minutes', models.PositiveIntegerField(default=0)),
('default_servings', models.DecimalField(decimal_places=2, default=2, max_digits=7, validators=[django.core.validators.MinValueValidator(Decimal('0.01'))])),
('category', models.CharField(blank=True, max_length=80)),
('tags', models.JSONField(blank=True, default=list)),
('is_favourite', models.BooleanField(default=False)),
('status', models.CharField(choices=[('draft', 'Draft'), ('published', 'Published')], default='draft', max_length=12)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('copied_from', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='copies', to='recipes.recipe')),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='recipes', to=settings.AUTH_USER_MODEL)),
('parent', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='variations', to='recipes.recipe')),
],
options={
'ordering': ('-updated_at', '-pk'),
},
),
migrations.CreateModel(
name='RecipeIngredient',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=180)),
('quantity', models.DecimalField(decimal_places=3, max_digits=10, validators=[django.core.validators.MinValueValidator(Decimal('0.001'))])),
('unit', models.CharField(choices=[('g', 'g'), ('kg', 'kg'), ('ml', 'ml'), ('L', 'L'), ('pieces', 'pieces'), ('tsp', 'tsp'), ('tbsp', 'tbsp'), ('portions', 'portions')], max_length=10)),
('display_order', models.PositiveIntegerField(default=0)),
('preparation_note', models.CharField(blank=True, max_length=255)),
('is_optional', models.BooleanField(default=False)),
('inventory_product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='recipe_inventory_ingredients', to='food.foodproduct')),
('nutrition_product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='recipe_nutrition_ingredients', to='food.foodproduct')),
('recipe', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ingredients', to='recipes.recipe')),
],
options={
'ordering': ('display_order', 'pk'),
},
),
migrations.CreateModel(
name='RecipeIngredientSubstitution',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=180)),
('quantity', models.DecimalField(decimal_places=3, max_digits=10, validators=[django.core.validators.MinValueValidator(Decimal('0.001'))])),
('unit', models.CharField(choices=[('g', 'g'), ('kg', 'kg'), ('ml', 'ml'), ('L', 'L'), ('pieces', 'pieces'), ('tsp', 'tsp'), ('tbsp', 'tbsp'), ('portions', 'portions')], max_length=10)),
('display_order', models.PositiveIntegerField(default=0)),
('ingredient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='substitutions', to='recipes.recipeingredient')),
('product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='recipe_substitutions', to='food.foodproduct')),
],
options={
'ordering': ('display_order', 'pk'),
},
),
migrations.CreateModel(
name='RecipeSubrecipe',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('quantity', models.DecimalField(decimal_places=3, default=1, max_digits=10, validators=[django.core.validators.MinValueValidator(Decimal('0.001'))])),
('unit', models.CharField(choices=[('servings', 'servings'), ('g', 'g'), ('ml', 'ml')], default='servings', max_length=16)),
('display_order', models.PositiveIntegerField(default=0)),
('note', models.CharField(blank=True, max_length=255)),
('component', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='used_in_recipes', to='recipes.recipe')),
('recipe', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='subrecipes', to='recipes.recipe')),
],
options={
'ordering': ('display_order', 'pk'),
},
),
migrations.AddConstraint(
model_name='recipe',
constraint=models.CheckConstraint(condition=models.Q(('default_servings__gt', 0)), name='recipes_positive_servings'),
),
migrations.AddConstraint(
model_name='recipeingredient',
constraint=models.CheckConstraint(condition=models.Q(('quantity__gt', 0)), name='recipes_positive_ingredient_quantity'),
),
migrations.AddConstraint(
model_name='recipesubrecipe',
constraint=models.UniqueConstraint(fields=('recipe', 'component'), name='recipes_unique_component'),
),
]
View File
+168
View File
@@ -0,0 +1,168 @@
"""Owned, structured recipes. Calculations and cooking workflows arrive in later passes."""
import uuid
from decimal import Decimal
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
class Recipe(models.Model):
class Status(models.TextChoices):
DRAFT = 'draft', 'Draft'
PUBLISHED = 'published', 'Published'
api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
related_name='recipes')
title = models.CharField(max_length=180)
description = models.TextField(blank=True)
instructions_markdown = models.TextField(blank=True)
notes_markdown = models.TextField(blank=True)
photo = models.ImageField(upload_to='recipes/%Y/%m/', blank=True)
preparation_minutes = models.PositiveIntegerField(default=0)
cooking_minutes = models.PositiveIntegerField(default=0)
default_servings = models.DecimalField(max_digits=7, decimal_places=2, default=2,
validators=[MinValueValidator(Decimal('0.01'))])
category = models.CharField(max_length=80, blank=True)
tags = models.JSONField(default=list, blank=True)
is_favourite = models.BooleanField(default=False)
status = models.CharField(max_length=12, choices=Status.choices, default=Status.DRAFT)
parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL,
related_name='variations')
copied_from = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL,
related_name='copies')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-updated_at', '-pk')
constraints = [models.CheckConstraint(condition=Q(default_servings__gt=0),
name='recipes_positive_servings')]
@property
def total_minutes(self):
return self.preparation_minutes + self.cooking_minutes
def clean(self):
super().clean()
if not isinstance(self.tags, list) or any(not isinstance(tag, str) for tag in self.tags):
raise ValidationError({'tags': 'Tags must be a list of names.'})
if self.parent_id:
if self.parent_id == self.pk:
raise ValidationError({'parent': 'A recipe cannot be its own variation.'})
if self.owner_id and self.parent.owner_id != self.owner_id:
raise ValidationError({'parent': 'Choose one of your own recipes.'})
seen = {self.pk}
cursor = self.parent
while cursor:
if cursor.pk in seen:
raise ValidationError({'parent': 'Variations cannot form a cycle.'})
seen.add(cursor.pk)
cursor = cursor.parent
if self.copied_from_id and self.owner_id and self.copied_from.owner_id != self.owner_id:
raise ValidationError({'copied_from': 'Choose one of your own recipes.'})
def __str__(self):
return self.title
class RecipeIngredient(models.Model):
class Unit(models.TextChoices):
GRAM = 'g', 'g'
KILOGRAM = 'kg', 'kg'
MILLILITRE = 'ml', 'ml'
LITRE = 'L', 'L'
PIECE = 'pieces', 'pieces'
TEASPOON = 'tsp', 'tsp'
TABLESPOON = 'tbsp', 'tbsp'
PORTION = 'portions', 'portions'
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='ingredients')
name = models.CharField(max_length=180)
quantity = models.DecimalField(max_digits=10, decimal_places=3,
validators=[MinValueValidator(Decimal('0.001'))])
unit = models.CharField(max_length=10, choices=Unit.choices)
display_order = models.PositiveIntegerField(default=0)
inventory_product = models.ForeignKey('food.FoodProduct', on_delete=models.SET_NULL,
null=True, blank=True, related_name='recipe_inventory_ingredients')
nutrition_product = models.ForeignKey('food.FoodProduct', on_delete=models.SET_NULL,
null=True, blank=True, related_name='recipe_nutrition_ingredients')
preparation_note = models.CharField(max_length=255, blank=True)
is_optional = models.BooleanField(default=False)
class Meta:
ordering = ('display_order', 'pk')
constraints = [models.CheckConstraint(condition=Q(quantity__gt=0),
name='recipes_positive_ingredient_quantity')]
def clean(self):
super().clean()
if self.recipe_id:
for field in ('inventory_product', 'nutrition_product'):
product = getattr(self, field)
if product and product.owner_id != self.recipe.owner_id:
raise ValidationError({field: 'Choose one of your own food products.'})
def __str__(self):
return f'{self.quantity} {self.unit} {self.name}'
class RecipeSubrecipe(models.Model):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='subrecipes')
component = models.ForeignKey(Recipe, on_delete=models.PROTECT, related_name='used_in_recipes')
quantity = models.DecimalField(max_digits=10, decimal_places=3, default=1,
validators=[MinValueValidator(Decimal('0.001'))])
unit = models.CharField(max_length=16, default='servings', choices=[
('servings', 'servings'), ('g', 'g'), ('ml', 'ml')])
display_order = models.PositiveIntegerField(default=0)
note = models.CharField(max_length=255, blank=True)
class Meta:
ordering = ('display_order', 'pk')
constraints = [models.UniqueConstraint(fields=('recipe', 'component'),
name='recipes_unique_component')]
def clean(self):
super().clean()
if self.recipe_id and self.component_id:
if self.recipe.owner_id != self.component.owner_id:
raise ValidationError({'component': 'Choose one of your own recipes.'})
if self.recipe_id == self.component_id:
raise ValidationError({'component': 'A recipe cannot contain itself.'})
seen = set()
pending = [self.component_id]
while pending:
current = pending.pop()
if current == self.recipe_id:
raise ValidationError({'component': 'Subrecipes cannot form a cycle.'})
if current not in seen:
seen.add(current)
pending.extend(RecipeSubrecipe.objects.filter(recipe_id=current)
.exclude(pk=self.pk).values_list('component_id', flat=True))
def __str__(self):
return f'{self.recipe} includes {self.component}'
class RecipeIngredientSubstitution(models.Model):
ingredient = models.ForeignKey(RecipeIngredient, on_delete=models.CASCADE,
related_name='substitutions')
name = models.CharField(max_length=180)
quantity = models.DecimalField(max_digits=10, decimal_places=3,
validators=[MinValueValidator(Decimal('0.001'))])
unit = models.CharField(max_length=10, choices=RecipeIngredient.Unit.choices)
product = models.ForeignKey('food.FoodProduct', on_delete=models.SET_NULL,
null=True, blank=True, related_name='recipe_substitutions')
display_order = models.PositiveIntegerField(default=0)
class Meta:
ordering = ('display_order', 'pk')
def clean(self):
super().clean()
if self.product_id and self.ingredient_id and self.product.owner_id != self.ingredient.recipe.owner_id:
raise ValidationError({'product': 'Choose one of your own food products.'})
+17
View File
@@ -0,0 +1,17 @@
(() => {
const button = document.querySelector('[data-add-ingredient]');
const container = document.querySelector('[data-ingredient-forms]');
const template = document.querySelector('#recipe-empty-ingredient');
const total = document.querySelector('#id_ingredients-TOTAL_FORMS');
if (!button || !container || !template || !total) return;
button.addEventListener('click', () => {
const index = Number(total.value);
const wrapper = document.createElement('div');
wrapper.innerHTML = template.innerHTML.replaceAll('__prefix__', String(index));
const row = wrapper.firstElementChild;
if (!row) return;
container.appendChild(row);
total.value = String(index + 1);
row.querySelector('input[name$="-name"]')?.focus();
});
})();
+14
View File
@@ -0,0 +1,14 @@
.page-content.recipes-page-content{max-width:1600px;padding:28px clamp(16px,3vw,32px) 72px}
.recipes-layout{--recipe-surface:#fff;--recipe-line:#e4e8e2;--recipe-ink:#25292e;--recipe-muted:#687178;--recipe-soft:#f5f7f3;--recipe-accent:#235943;display:grid;grid-template-columns:minmax(260px,340px) minmax(0,1fr) minmax(245px,290px);gap:20px;align-items:start;width:100%;max-width:1600px;margin-inline:auto;color:var(--recipe-ink)}
.recipes-layout *{box-sizing:border-box}.recipes-layout a:focus-visible,.recipes-layout button:focus-visible,.recipes-layout input:focus-visible,.recipes-layout select:focus-visible,.recipes-layout textarea:focus-visible,.recipes-layout summary:focus-visible{outline:3px solid #77b68b;outline-offset:3px}
.recipes-browser,.recipes-detail,.recipes-info{min-width:0}.recipes-browser__heading{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;margin:0 0 18px}.recipes-browser__heading h1{margin:0 0 2px;font-size:2.35rem}.recipes-browser__heading p{margin:0;color:var(--recipe-muted);font-size:.85rem}.recipes-new{flex:none;min-height:42px;margin-top:4px;padding-inline:14px;white-space:nowrap}
.recipes-filters{display:grid;gap:12px;margin:0 0 16px}.recipes-filters>label:first-child{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0)}.recipes-search-row{display:flex;gap:7px}.recipes-search-row input{flex:1;min-width:0}.recipes-search-row button,.recipes-filter-apply,.recipes-outline-button{min-height:42px;padding:8px 12px;border:1px solid #d7dcd5;border-radius:9px;color:var(--recipe-ink);background:var(--recipe-surface);font-size:.81rem;font-weight:700;text-decoration:none}.recipes-search-row button:hover,.recipes-filter-apply:hover,.recipes-outline-button:hover{border-color:var(--recipe-accent);color:var(--recipe-accent)}.recipes-search-row input,.recipes-filter-grid select{width:100%;min-height:42px;padding:9px 11px;border:1px solid #d7dcd5;border-radius:9px;color:var(--recipe-ink);background:var(--recipe-surface)}.recipes-filter-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px}.recipes-filter-grid label{min-width:0;color:var(--recipe-muted);font-size:.75rem;font-weight:700}.recipes-filter-grid select{margin-top:4px}.recipes-favourite-filter{display:flex;align-items:center;gap:7px;color:var(--recipe-ink);font-size:.82rem}.recipes-favourite-filter input{width:17px;height:17px;accent-color:var(--recipe-accent)}.recipes-filter-apply{justify-self:start}
.recipes-list{display:grid;gap:8px}.recipes-list-item{display:flex;align-items:center;gap:11px;min-height:86px;padding:9px;border:1px solid var(--recipe-line);border-radius:13px;color:inherit;background:var(--recipe-surface);text-decoration:none}.recipes-list-item:hover,.recipes-list-item--selected{border-color:#69a581;background:#f8fcf8}.recipes-list-item__image,.recipes-list-item__placeholder{flex:none;width:68px;height:68px;border-radius:9px;object-fit:cover}.recipes-list-item__placeholder{display:grid;place-items:center;color:#3f6954;background:#e1eee5;font-family:Fraunces,Georgia,serif;font-size:.72rem;font-weight:700}.recipes-list-item__body{display:grid;gap:1px;min-width:0}.recipes-list-item__body strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:Fraunces,Georgia,serif;font-size:.96rem;line-height:1.2}.recipes-list-item__body small{color:var(--recipe-muted);font-size:.73rem}.recipes-list-item__tags,.recipes-chips{display:flex;flex-wrap:wrap;gap:5px;margin-top:4px}.recipes-list-item__tags span,.recipes-chips span{padding:3px 8px;border-radius:999px;background:#eef1ed;font-size:.7rem}.recipes-list-item__favourite{align-self:flex-start;margin-left:auto;color:#bd4e48;font-size:1rem}.recipes-empty-list{padding:24px;border:1px dashed var(--recipe-line);border-radius:13px;background:var(--recipe-surface)}.recipes-empty-list p{margin:0 0 8px}.recipes-empty-list a{color:var(--recipe-accent)}
.recipes-detail{min-height:560px;padding:20px;border:1px solid var(--recipe-line);border-radius:17px;background:var(--recipe-surface);box-shadow:0 12px 35px rgba(29,43,37,.045)}.recipes-detail__top{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:0 0 17px}.recipes-back{color:var(--recipe-accent);font-size:.8rem;font-weight:700;text-decoration:none}.recipes-back:hover{text-decoration:underline}.recipes-detail__top-actions{display:flex;align-items:center;gap:7px}.recipes-detail__top-actions form{margin:0}.recipes-heart{display:grid;place-items:center;width:42px;height:42px;padding:0;border:0;color:#bd4e48;background:transparent;font-size:1.6rem}.recipes-hero{display:grid;grid-template-columns:minmax(180px,42%) minmax(0,1fr);gap:22px;align-items:start;padding-bottom:21px;border-bottom:1px solid var(--recipe-line)}.recipes-hero>img,.recipes-photo-placeholder{display:block;width:100%;height:220px;border-radius:12px;object-fit:cover}.recipes-photo-placeholder{display:grid;place-items:center;border:1px dashed #acc8b4;color:#466c54;background:#e5f1e8;font-family:Fraunces,Georgia,serif}.recipes-hero__copy{min-width:0}.recipes-eyebrow{margin:0 0 4px;color:var(--recipe-accent);font-size:.7rem;font-weight:700;letter-spacing:.1em;text-transform:uppercase}.recipes-hero h2{margin:0 0 9px;font-size:clamp(1.8rem,2.6vw,2.7rem);line-height:1.12}.recipes-hero__meta{margin:0;color:var(--recipe-muted);font-size:.85rem}.recipes-chips{margin-top:11px}.recipes-chips span{padding:5px 10px;font-size:.73rem}.recipes-hero__description{margin:14px 0 0;color:var(--recipe-muted);font-size:.88rem;line-height:1.6}.recipes-content-grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:12px;margin-top:18px}.recipes-content-stack{display:grid;gap:12px;align-content:start}.recipes-panel{min-width:0;padding:17px;border:1px solid var(--recipe-line);border-radius:13px;background:var(--recipe-surface)}.recipes-panel h3{margin:0 0 13px;font-family:Fraunces,Georgia,serif;font-size:1.05rem}.recipes-ingredient-list{padding:0;margin:0;list-style:none}.recipes-ingredient-list li{display:flex;flex-wrap:wrap;align-items:baseline;justify-content:space-between;gap:4px 12px;padding:10px 0;border-bottom:1px solid var(--recipe-line);font-size:.83rem}.recipes-ingredient-list li:last-child{border-bottom:0}.recipes-ingredient-list small{display:block;color:var(--recipe-muted)}.recipes-ingredient-list strong{white-space:nowrap;font-weight:700}.recipes-ingredient-list em{width:100%;color:var(--recipe-muted);font-size:.72rem}.recipes-markdown-source{overflow-wrap:anywhere;font-size:.86rem;line-height:1.65}.recipes-muted{color:var(--recipe-muted);font-size:.84rem}.recipes-empty-detail{display:grid;align-content:center;justify-items:start;min-height:490px;max-width:470px;margin:auto}.recipes-empty-detail h2{margin:0 0 9px;font-size:2rem}.recipes-empty-detail p{color:var(--recipe-muted)}
.recipes-info{display:grid;gap:12px}.recipes-info .recipes-panel{padding:18px}.recipes-facts{margin:0}.recipes-facts div{display:flex;justify-content:space-between;gap:8px;padding:8px 0;border-bottom:1px solid var(--recipe-line);font-size:.82rem}.recipes-facts div:last-child{border-bottom:0}.recipes-facts dt{color:var(--recipe-muted)}.recipes-facts dd{margin:0;font-weight:700}.recipes-info p{margin:0 0 9px;font-size:.82rem}.recipes-info p:last-child{margin-bottom:0}.recipes-info a:not(.recipes-action){color:var(--recipe-accent)}.recipes-action{display:block;padding:9px 0;border-bottom:1px solid var(--recipe-line);font-size:.84rem;text-decoration:none}.recipes-action:last-child{border:0}.recipes-action--danger{color:#b6413b}
.recipes-layout--form{display:block;max-width:1100px}.recipes-form-header{margin:0 0 23px}.recipes-form-header>a{color:var(--recipe-accent);font-size:.85rem;font-weight:700}.recipes-form-header h1{margin:8px 0 4px;font-size:2.7rem}.recipes-form-header p{margin:0;color:var(--recipe-muted)}.recipes-edit-card{display:grid;gap:28px;padding:24px;border:1px solid var(--recipe-line);border-radius:17px;background:var(--recipe-surface)}.recipes-edit-card section+section{padding-top:24px;border-top:1px solid var(--recipe-line)}.recipes-edit-card h2{margin:0 0 16px;font-size:1.25rem}.recipes-form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.recipes-field{min-width:0}.recipes-field label:not(.recipes-checkbox){display:block;margin:0 0 5px;font-size:.81rem;font-weight:700}.recipes-field input:not([type=checkbox]),.recipes-field textarea,.recipes-field select{width:100%;min-height:43px;padding:9px 10px;border:1px solid #cbd3cb;border-radius:8px;color:var(--recipe-ink);background:var(--recipe-surface)}.recipes-field textarea{min-height:94px;resize:vertical}.recipes-field small{display:block;margin-top:4px;color:var(--recipe-muted);font-size:.73rem}.recipes-field--title,.recipes-field--description,.recipes-field--instructions_markdown,.recipes-field--notes_markdown,.recipes-field--photo,.recipes-field--remove_photo{grid-column:1/-1}.recipes-field--photo input{height:auto}.recipes-checkbox{display:inline-flex;align-items:center;gap:7px;font-size:.8rem}.recipes-checkbox input{width:17px;height:17px;accent-color:var(--recipe-accent)}.recipes-current-photo{display:block;width:170px;max-height:120px;margin:0 0 9px;border-radius:9px;object-fit:cover}.recipes-section-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px}.recipes-section-heading h2{margin:0 0 2px}.recipes-section-heading p{margin:0;color:var(--recipe-muted);font-size:.8rem}.recipes-ingredient-forms{display:grid;gap:12px}.recipes-ingredient-form{padding:14px;border:1px solid var(--recipe-line);border-radius:12px;background:var(--recipe-soft)}.recipes-ingredient-form__main{display:grid;grid-template-columns:minmax(0,1fr) 110px 120px;gap:10px}.recipes-ingredient-form__more{margin-top:9px}.recipes-ingredient-form__more summary{color:var(--recipe-accent);font-size:.8rem;cursor:pointer}.recipes-ingredient-form__more .recipes-form-grid{padding-top:12px}.recipes-form-error,.recipes-field .errorlist{margin:7px 0;color:#b6413b;font-size:.8rem}.recipes-form-actions{display:flex;align-items:center;gap:20px;padding-top:19px;border-top:1px solid var(--recipe-line)}.recipes-form-actions>a,.recipes-delete a{color:var(--recipe-accent)}.recipes-delete{max-width:620px}.recipes-delete h1{font-size:2.3rem}.recipes-delete form{display:flex;align-items:center;gap:20px}
body[data-theme=dark] .recipes-layout{--recipe-surface:#222b25;--recipe-line:#435046;--recipe-ink:#eaf0ea;--recipe-muted:#afbbb2;--recipe-soft:#29352d;--recipe-accent:#a7d9b6}body[data-theme=dark] .recipes-list-item:hover,body[data-theme=dark] .recipes-list-item--selected{background:#2a3b30}body[data-theme=dark] .recipes-list-item__placeholder,body[data-theme=dark] .recipes-photo-placeholder{color:#b8e4c5;background:#314d39;border-color:#5d8968}body[data-theme=dark] .recipes-list-item__tags span,body[data-theme=dark] .recipes-chips span{background:#354339}body[data-theme=dark] .recipes-search-row button,body[data-theme=dark] .recipes-filter-apply,body[data-theme=dark] .recipes-outline-button,body[data-theme=dark] .recipes-search-row input,body[data-theme=dark] .recipes-filter-grid select,body[data-theme=dark] .recipes-field input:not([type=checkbox]),body[data-theme=dark] .recipes-field textarea,body[data-theme=dark] .recipes-field select{border-color:#526055;background:var(--recipe-surface);color:var(--recipe-ink)}
@media(max-width:1399px){.recipes-layout:not(.recipes-layout--form){grid-template-columns:minmax(260px,320px) minmax(0,1fr)}.recipes-info{grid-column:2;grid-template-columns:repeat(2,minmax(0,1fr))}.recipes-info .recipes-panel:last-child{grid-column:1/-1}.recipes-hero{grid-template-columns:minmax(170px,40%) minmax(0,1fr)}}
@media(max-width:991px){.recipes-layout:not(.recipes-layout--form){grid-template-columns:minmax(0,1fr)}.recipes-browser,.recipes-detail,.recipes-info{grid-column:1}.recipes-list{grid-template-columns:repeat(2,minmax(0,1fr))}.recipes-hero{grid-template-columns:minmax(170px,38%) minmax(0,1fr)}.recipes-info{grid-template-columns:repeat(2,minmax(0,1fr))}.recipes-info .recipes-panel:last-child{grid-column:auto}}
@media(max-width:767px){.page-content.recipes-page-content{padding-top:25px}.recipes-layout--list .recipes-detail,.recipes-layout--list .recipes-info{display:none}.recipes-layout--detail .recipes-browser{display:none}.recipes-browser__heading h1{font-size:2.4rem}.recipes-detail{padding:16px}.recipes-hero{grid-template-columns:1fr;gap:15px}.recipes-hero>img,.recipes-photo-placeholder{height:230px}.recipes-hero h2{font-size:2rem}.recipes-content-grid,.recipes-info{grid-template-columns:1fr}.recipes-list{grid-template-columns:1fr}.recipes-form-grid{grid-template-columns:1fr}.recipes-field--title,.recipes-field--description,.recipes-field--instructions_markdown,.recipes-field--notes_markdown,.recipes-field--photo,.recipes-field--remove_photo{grid-column:auto}.recipes-ingredient-form__main{grid-template-columns:minmax(0,1fr) minmax(90px,1fr)}.recipes-ingredient-form__main .recipes-field:first-child{grid-column:1/-1}.recipes-edit-card{padding:18px}.recipes-section-heading{align-items:flex-start;flex-wrap:wrap}.recipes-section-heading button{width:100%}}
@media(max-width:400px){.recipes-browser__heading{display:block}.recipes-new{margin-top:12px}.recipes-filter-grid{grid-template-columns:1fr}.recipes-detail__top{flex-wrap:wrap}.recipes-ingredient-form__main{grid-template-columns:1fr 1fr}}
@@ -0,0 +1,4 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Delete {{ recipe.title }} · Tasknest{% endblock %}
{% block page_class %}recipes-page-content{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}"><div class="recipes-layout recipes-layout--form"><section class="recipes-edit-card recipes-delete"><h1>Delete {{ recipe.title }}?</h1><p>This removes the recipe and its ingredients. This action cannot be undone.</p><form method="post">{% csrf_token %}<button type="submit" class="button button--danger">Delete recipe</button><a href="{% url 'recipes:detail' recipe.api_id %}">Cancel</a></form></section></div>{% endblock %}
+11
View File
@@ -0,0 +1,11 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}{% if creating %}New recipe{% else %}Edit {{ recipe.title }}{% endif %} · Tasknest{% endblock %}
{% block page_class %}recipes-page-content{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}">
<div class="recipes-layout recipes-layout--form"><header class="recipes-form-header"><a href="{% if creating %}{% url 'recipes:list' %}{% else %}{% url 'recipes:detail' recipe.api_id %}{% endif %}">← Back to recipes</a><h1>{% if creating %}New recipe{% else %}Edit recipe{% endif %}</h1><p>Keep ingredients structured and instructions in Markdown.</p></header>
<form method="post" enctype="multipart/form-data" class="recipes-edit-card" data-recipe-form>{% csrf_token %}
{% if form.non_field_errors %}<div class="recipes-form-error" role="alert">{{ form.non_field_errors }}</div>{% endif %}
<section><h2>Recipe details</h2><div class="recipes-form-grid">{% for field in form %}{% if field.name != 'remove_photo' %}<div class="recipes-field recipes-field--{{ field.name }}"><label for="{{ field.id_for_label }}">{{ field.label }}</label>{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{% if field.errors %}<div class="recipes-form-error" role="alert">{{ field.errors }}</div>{% endif %}</div>{% endif %}{% endfor %}{% if recipe.photo %}<div class="recipes-field recipes-field--remove_photo"><img src="{% url 'recipes:photo' recipe.api_id %}" alt="Current recipe photo" class="recipes-current-photo"><label class="recipes-checkbox">{{ form.remove_photo }} Remove current photo</label></div>{% endif %}</div></section>
<section><div class="recipes-section-heading"><div><h2>Ingredients</h2><p>Add measured ingredients now; product matching can be refined later.</p></div><button type="button" class="recipes-outline-button" data-add-ingredient>+ Add ingredient</button></div>{{ ingredients.management_form }}{% if ingredients.non_form_errors %}<div class="recipes-form-error" role="alert">{{ ingredients.non_form_errors }}</div>{% endif %}<div class="recipes-ingredient-forms" data-ingredient-forms>{% for ingredient in ingredients %}{% include 'recipes/ingredient_row.html' %}{% endfor %}</div><template id="recipe-empty-ingredient">{% with ingredient=ingredients.empty_form %}{% include 'recipes/ingredient_row.html' %}{% endwith %}</template></section>
<div class="recipes-form-actions"><button type="submit" class="button">Save recipe</button><a href="{% if creating %}{% url 'recipes:list' %}{% else %}{% url 'recipes:detail' recipe.api_id %}{% endif %}">Cancel</a></div>
</form></div><script defer src="{% static 'recipes/form.js' %}"></script>{% endblock %}
@@ -0,0 +1,6 @@
<div class="recipes-ingredient-form" data-ingredient-row>
{% for hidden in ingredient.hidden_fields %}{{ hidden }}{% endfor %}
<div class="recipes-ingredient-form__main"><div class="recipes-field"><label for="{{ ingredient.name.id_for_label }}">Ingredient name</label>{{ ingredient.name }}{{ ingredient.name.errors }}</div><div class="recipes-field"><label for="{{ ingredient.quantity.id_for_label }}">Quantity</label>{{ ingredient.quantity }}{{ ingredient.quantity.errors }}</div><div class="recipes-field"><label for="{{ ingredient.unit.id_for_label }}">Unit</label>{{ ingredient.unit }}{{ ingredient.unit.errors }}</div></div>
<details class="recipes-ingredient-form__more"><summary>Ingredient details</summary><div class="recipes-form-grid"><div class="recipes-field"><label for="{{ ingredient.preparation_note.id_for_label }}">Preparation note</label>{{ ingredient.preparation_note }}{{ ingredient.preparation_note.errors }}</div><div class="recipes-field"><label for="{{ ingredient.display_order.id_for_label }}">Display order</label>{{ ingredient.display_order }}{{ ingredient.display_order.errors }}</div><div class="recipes-field"><label for="{{ ingredient.inventory_product.id_for_label }}">Inventory product</label>{{ ingredient.inventory_product }}{{ ingredient.inventory_product.errors }}</div><div class="recipes-field"><label for="{{ ingredient.nutrition_product.id_for_label }}">Nutrition product</label>{{ ingredient.nutrition_product }}{{ ingredient.nutrition_product.errors }}</div><label class="recipes-checkbox">{{ ingredient.is_optional }} Optional ingredient</label>{% if ingredient.DELETE %}<label class="recipes-checkbox">{{ ingredient.DELETE }} Remove ingredient</label>{% endif %}</div></details>
{% if ingredient.non_field_errors %}<div class="recipes-form-error" role="alert">{{ ingredient.non_field_errors }}</div>{% endif %}
</div>
@@ -0,0 +1,57 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Recipes · Tasknest{% endblock %}
{% block page_class %}recipes-page-content{% endblock %}
{% block content %}
<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}">
<div class="recipes-layout {% if explicit_detail %}recipes-layout--detail{% else %}recipes-layout--list{% endif %}">
<aside class="recipes-browser" aria-label="Recipe browser">
<div class="recipes-browser__heading">
<div><h1>Recipes</h1><p>Find, create and cook with what you have.</p></div>
<a class="button recipes-new" href="{% url 'recipes:create' %}">+ New recipe</a>
</div>
<form method="get" action="{% url 'recipes:list' %}" class="recipes-filters" role="search">
<label for="recipes-search">Search recipes</label>
<div class="recipes-search-row"><input id="recipes-search" type="search" name="q" value="{{ query }}" placeholder="Search recipes or ingredients"><button type="submit">Search</button></div>
<div class="recipes-filter-grid">
<label>Category<select name="category"><option value="">All categories</option>{% for value in categories %}<option value="{{ value }}"{% if value == category %} selected{% endif %}>{{ value }}</option>{% endfor %}</select></label>
<label>Tag<select name="tag"><option value="">All tags</option>{% for value in tags %}<option value="{{ value }}"{% if value == tag %} selected{% endif %}>{{ value }}</option>{% endfor %}</select></label>
</div>
<label class="recipes-favourite-filter"><input type="checkbox" name="favourite" value="1"{% if favourite %} checked{% endif %}> Favourites only</label>
<button class="recipes-filter-apply" type="submit">Apply filters</button>
</form>
<div class="recipes-list" aria-label="Your recipes">
{% for recipe in recipes %}
<a class="recipes-list-item{% if selected.pk == recipe.pk %} recipes-list-item--selected{% endif %}" href="{% url 'recipes:detail' recipe.api_id %}{% if request.GET %}?{{ request.GET.urlencode }}{% endif %}"{% if selected.pk == recipe.pk %} aria-current="page"{% endif %}>
{% if recipe.photo %}<img class="recipes-list-item__image" src="{% url 'recipes:photo' recipe.api_id %}" alt="" loading="lazy">{% else %}<span class="recipes-list-item__placeholder" aria-hidden="true">Recipe</span>{% endif %}
<span class="recipes-list-item__body"><strong>{{ recipe.title }}</strong><small>{{ recipe.total_minutes }} min · {{ recipe.default_servings|floatformat:-2 }} servings</small><span class="recipes-list-item__tags">{% if recipe.category %}<span>{{ recipe.category }}</span>{% endif %}{% for value in recipe.tags|slice:':2' %}<span>{{ value }}</span>{% endfor %}</span></span>
{% if recipe.is_favourite %}<span class="recipes-list-item__favourite" aria-label="Favourite">♥</span>{% endif %}
</a>
{% empty %}
<div class="recipes-empty-list"><p>{% if query or category or tag or favourite %}No recipes match these filters.{% else %}Your recipe library is ready.{% endif %}</p><a href="{% url 'recipes:create' %}">Create a recipe</a></div>
{% endfor %}
</div>
</aside>
<section class="recipes-detail" aria-label="Recipe details">
{% if selected %}
<div class="recipes-detail__top"><a class="recipes-back" href="{% url 'recipes:list' %}">← Back to recipes</a><div class="recipes-detail__top-actions"><form method="post" action="{% url 'recipes:favourite' selected.api_id %}">{% csrf_token %}<button type="submit" class="recipes-heart" aria-label="{% if selected.is_favourite %}Remove {{ selected.title }} from favourites{% else %}Add {{ selected.title }} to favourites{% endif %}" aria-pressed="{% if selected.is_favourite %}true{% else %}false{% endif %}">{% if selected.is_favourite %}♥{% else %}♡{% endif %}</button></form><a class="recipes-outline-button" href="{% url 'recipes:edit' selected.api_id %}">Edit</a></div></div>
<div class="recipes-hero">
{% if selected.photo %}<img src="{% url 'recipes:photo' selected.api_id %}" alt="Photo of {{ selected.title }}">{% else %}<div class="recipes-photo-placeholder" role="img" aria-label="No recipe photo yet"><span>No photo yet</span></div>{% endif %}
<div class="recipes-hero__copy"><p class="recipes-eyebrow">{% if selected.status == 'draft' %}Draft recipe{% else %}Recipe{% endif %}</p><h2>{{ selected.title }}</h2><p class="recipes-hero__meta">{{ selected.total_minutes }} min total · {{ selected.default_servings|floatformat:-2 }} servings</p><div class="recipes-chips">{% if selected.category %}<span>{{ selected.category }}</span>{% endif %}{% for value in selected.tags %}<span>{{ value }}</span>{% endfor %}</div>{% if selected.description %}<p class="recipes-hero__description">{{ selected.description }}</p>{% endif %}</div>
</div>
<div class="recipes-content-grid">
<section class="recipes-panel" aria-labelledby="recipe-ingredients-heading"><h3 id="recipe-ingredients-heading">Ingredients</h3><ul class="recipes-ingredient-list">{% for ingredient in selected.ingredients.all %}<li><span>{{ ingredient.name }}{% if ingredient.preparation_note %}<small>{{ ingredient.preparation_note }}</small>{% endif %}</span><strong>{{ ingredient.quantity|floatformat:-3 }} {{ ingredient.unit }}</strong>{% if ingredient.is_optional %}<em>Optional</em>{% endif %}</li>{% empty %}<li class="recipes-muted">No ingredients added yet.</li>{% endfor %}</ul></section>
<div class="recipes-content-stack"><section class="recipes-panel" aria-labelledby="recipe-instructions-heading"><h3 id="recipe-instructions-heading">Instructions</h3>{% if selected.instructions_markdown %}<div class="recipes-markdown-source">{{ selected.instructions_markdown|linebreaksbr }}</div>{% else %}<p class="recipes-muted">No instructions added yet.</p>{% endif %}</section>{% if selected.notes_markdown %}<section class="recipes-panel" aria-labelledby="recipe-notes-heading"><h3 id="recipe-notes-heading">Notes</h3><div class="recipes-markdown-source">{{ selected.notes_markdown|linebreaksbr }}</div></section>{% endif %}</div>
</div>
{% else %}
<div class="recipes-empty-detail"><h2>Make room for something delicious.</h2><p>Save a recipe to see its ingredients and instructions here.</p><a class="button" href="{% url 'recipes:create' %}">Create your first recipe</a></div>
{% endif %}
</section>
{% if selected %}<aside class="recipes-info" aria-label="Recipe information">
<section class="recipes-panel"><h3>At a glance</h3><dl class="recipes-facts"><div><dt>Servings</dt><dd>{{ selected.default_servings|floatformat:-2 }}</dd></div><div><dt>Preparation</dt><dd>{{ selected.preparation_minutes }} min</dd></div><div><dt>Cooking</dt><dd>{{ selected.cooking_minutes }} min</dd></div><div><dt>Status</dt><dd>{{ selected.get_status_display }}</dd></div></dl></section>
{% if selected.parent or selected.variations.all or selected.subrecipes.all %}<section class="recipes-panel"><h3>Related recipes</h3>{% if selected.parent %}<p>Variation of <a href="{% url 'recipes:detail' selected.parent.api_id %}">{{ selected.parent.title }}</a></p>{% endif %}{% for variation in selected.variations.all %}<p><a href="{% url 'recipes:detail' variation.api_id %}">{{ variation.title }}</a></p>{% endfor %}{% for item in selected.subrecipes.all %}<p>{{ item.quantity|floatformat:-3 }} {{ item.unit }} of <a href="{% url 'recipes:detail' item.component.api_id %}">{{ item.component.title }}</a></p>{% endfor %}</section>{% endif %}
<section class="recipes-panel"><h3>Actions</h3><a class="recipes-action" href="{% url 'recipes:edit' selected.api_id %}">Edit recipe</a><a class="recipes-action recipes-action--danger" href="{% url 'recipes:delete' selected.api_id %}">Delete recipe</a></section>
</aside>{% endif %}
</div>
{% endblock %}
+95
View File
@@ -0,0 +1,95 @@
from decimal import Decimal
from io import BytesIO
from tempfile import TemporaryDirectory
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
from PIL import Image
from .models import Recipe, RecipeIngredient, RecipeSubrecipe
class RecipeWebTests(TestCase):
def setUp(self):
user_model = get_user_model()
self.user = user_model.objects.create_user(username='cook', password='test-password')
self.other = user_model.objects.create_user(username='other', password='test-password')
self.client.force_login(self.user)
def data(self, title='Noodles', **changes):
data = {
'title': title, 'description': 'A weeknight meal', 'category': 'Dinner',
'preparation_minutes': '10', 'cooking_minutes': '15',
'default_servings': '2', 'status': 'draft', 'tags_text': 'Asian, Quick',
'instructions_markdown': 'Cook the noodles.', 'notes_markdown': '',
'ingredients-TOTAL_FORMS': '1', 'ingredients-INITIAL_FORMS': '0',
'ingredients-MIN_NUM_FORMS': '0', 'ingredients-MAX_NUM_FORMS': '1000',
'ingredients-0-name': 'Noodles', 'ingredients-0-quantity': '250',
'ingredients-0-unit': 'g', 'ingredients-0-display_order': '0',
}
data.update(changes)
return data
def test_create_search_filter_edit_favourite_and_delete(self):
response = self.client.post(reverse('recipes:create'), self.data())
self.assertEqual(response.status_code, 302)
recipe = Recipe.objects.get(owner=self.user)
self.assertEqual(recipe.tags, ['Asian', 'Quick'])
self.assertEqual(recipe.ingredients.get().quantity, Decimal('250'))
self.assertContains(self.client.get(reverse('recipes:list'), {'q': 'Noodles'}), 'Noodles')
self.assertContains(self.client.get(reverse('recipes:list'), {'tag': 'Asian'}), 'Noodles')
self.assertNotContains(self.client.get(reverse('recipes:list'), {'tag': 'Other'}), 'A weeknight meal')
self.client.post(reverse('recipes:favourite', args=[recipe.api_id]))
recipe.refresh_from_db()
self.assertTrue(recipe.is_favourite)
edit_data = self.data('Updated noodles', **{
'ingredients-INITIAL_FORMS': '1', 'ingredients-0-id': str(recipe.ingredients.get().pk),
'ingredients-0-quantity': '300',
})
self.assertEqual(self.client.post(reverse('recipes:edit', args=[recipe.api_id]), edit_data).status_code, 302)
recipe.refresh_from_db()
self.assertEqual(recipe.title, 'Updated noodles')
self.assertEqual(recipe.ingredients.get().quantity, Decimal('300'))
self.assertEqual(self.client.post(reverse('recipes:delete', args=[recipe.api_id])).status_code, 302)
self.assertFalse(Recipe.objects.filter(pk=recipe.pk).exists())
def test_owner_isolation(self):
recipe = Recipe.objects.create(owner=self.other, title='Private')
for name in ('detail', 'edit', 'delete', 'photo'):
self.assertEqual(self.client.get(reverse(f'recipes:{name}', args=[recipe.api_id])).status_code, 404)
self.assertEqual(self.client.post(reverse('recipes:favourite', args=[recipe.api_id])).status_code, 404)
self.assertNotContains(self.client.get(reverse('recipes:list')), 'Private')
def test_invalid_ingredient_does_not_create_recipe(self):
response = self.client.post(reverse('recipes:create'), self.data(**{'ingredients-0-quantity': '-1'}))
self.assertEqual(response.status_code, 200)
self.assertFalse(Recipe.objects.exists())
def test_subrecipe_ownership_and_cycles(self):
a = Recipe.objects.create(owner=self.user, title='A')
b = Recipe.objects.create(owner=self.user, title='B')
other = Recipe.objects.create(owner=self.other, title='Other')
RecipeSubrecipe.objects.create(recipe=a, component=b)
with self.assertRaises(ValidationError):
RecipeSubrecipe(recipe=b, component=a).full_clean()
with self.assertRaises(ValidationError):
RecipeSubrecipe(recipe=a, component=other).full_clean()
with self.assertRaises(ValidationError):
RecipeIngredient(recipe=a, name='Flour', quantity=Decimal('-1'), unit='g').full_clean()
def test_photo_upload_is_private(self):
image = BytesIO()
Image.new('RGB', (2, 2), '#217857').save(image, format='PNG')
with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
data = self.data()
data['photo'] = SimpleUploadedFile('noodles.png', image.getvalue(), content_type='image/png')
self.assertEqual(self.client.post(reverse('recipes:create'), data).status_code, 302)
recipe = Recipe.objects.get(owner=self.user)
photo_url = reverse('recipes:photo', args=[recipe.api_id])
self.assertEqual(self.client.get(photo_url).status_code, 200)
self.client.force_login(self.other)
self.assertEqual(self.client.get(photo_url).status_code, 404)
+15
View File
@@ -0,0 +1,15 @@
from django.urls import path
from . import views
app_name = 'recipes'
urlpatterns = [
path('', views.library, name='list'),
path('new/', views.create, name='create'),
path('<uuid:identifier>/', views.detail, name='detail'),
path('<uuid:identifier>/edit/', views.edit, name='edit'),
path('<uuid:identifier>/delete/', views.delete, name='delete'),
path('<uuid:identifier>/favourite/', views.toggle_favourite, name='favourite'),
path('<uuid:identifier>/photo/', views.photo, name='photo'),
]
+144
View File
@@ -0,0 +1,144 @@
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.db.models import Q
from django.http import FileResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.views.decorators.http import require_http_methods, require_POST
from PIL import Image
from .forms import RecipeForm, RecipeIngredientFormSet
from .models import Recipe
def _owned(user):
return Recipe.objects.filter(owner=user)
def _library(request, selected=None):
explicit_detail = selected is not None
recipes = _owned(request.user).prefetch_related('ingredients')
query = request.GET.get('q', '').strip()[:100]
category = request.GET.get('category', '').strip()[:80]
tag = request.GET.get('tag', '').strip()[:40]
favourite = request.GET.get('favourite') == '1'
if query:
recipes = recipes.filter(Q(title__icontains=query) | Q(description__icontains=query) |
Q(ingredients__name__icontains=query)).distinct()
if category:
recipes = recipes.filter(category=category)
if favourite:
recipes = recipes.filter(is_favourite=True)
recipes = list(recipes)
if tag:
recipes = [recipe for recipe in recipes if tag in recipe.tags]
recipes = recipes[:100]
if selected is None and recipes:
selected = recipes[0]
categories = list(_owned(request.user).exclude(category='').order_by('category')
.values_list('category', flat=True).distinct())
tags = sorted({tag for values in _owned(request.user).values_list('tags', flat=True)
for tag in values if isinstance(tag, str)})
return render(request, 'recipes/library.html', {
'recipes': recipes, 'selected': selected, 'query': query,
'category': category, 'tag': tag, 'favourite': favourite,
'categories': categories, 'tags': tags, 'explicit_detail': explicit_detail,
})
@login_required
def library(request):
return _library(request)
@login_required
def detail(request, identifier):
recipe = get_object_or_404(_owned(request.user).select_related('parent')
.prefetch_related('ingredients', 'subrecipes__component', 'variations'), api_id=identifier)
return _library(request, recipe)
def _edit(request, recipe=None):
creating = recipe is None
recipe = recipe or Recipe(owner=request.user)
old_photo = recipe.photo.name if recipe.pk and recipe.photo else ''
form = RecipeForm(request.POST or None, request.FILES or None,
instance=recipe, user=request.user)
ingredients = RecipeIngredientFormSet(request.POST or None, instance=recipe,
prefix='ingredients', user=request.user)
if request.method == 'POST' and form.is_valid() and ingredients.is_valid():
with transaction.atomic():
recipe = form.save(commit=False)
recipe.owner = request.user
if form.cleaned_data['remove_photo']:
recipe.photo = ''
recipe.full_clean()
recipe.save()
ingredients.instance = recipe
ingredients.save()
if old_photo and old_photo != recipe.photo.name:
transaction.on_commit(lambda: recipe.photo.storage.delete(old_photo))
messages.success(request, 'Recipe saved.')
return redirect('recipes:detail', identifier=recipe.api_id)
return render(request, 'recipes/form.html', {
'form': form, 'ingredients': ingredients, 'recipe': recipe,
'creating': creating,
})
@login_required
@require_http_methods(['GET', 'POST'])
def create(request):
return _edit(request)
@login_required
@require_http_methods(['GET', 'POST'])
def edit(request, identifier):
return _edit(request, get_object_or_404(_owned(request.user), api_id=identifier))
@login_required
@require_http_methods(['GET', 'POST'])
def delete(request, identifier):
recipe = get_object_or_404(_owned(request.user), api_id=identifier)
if request.method == 'POST':
if recipe.used_in_recipes.exists():
messages.error(request, 'Remove this recipe from other recipes before deleting it.')
return redirect('recipes:detail', identifier=recipe.api_id)
photo = recipe.photo.name if recipe.photo else ''
with transaction.atomic():
recipe.delete()
if photo:
transaction.on_commit(lambda: recipe.photo.storage.delete(photo))
messages.success(request, 'Recipe deleted.')
return redirect('recipes:list')
return render(request, 'recipes/delete.html', {'recipe': recipe})
@login_required
@require_POST
def toggle_favourite(request, identifier):
recipe = get_object_or_404(_owned(request.user), api_id=identifier)
recipe.is_favourite = not recipe.is_favourite
recipe.save(update_fields=('is_favourite', 'updated_at'))
return redirect('recipes:detail', identifier=recipe.api_id)
@login_required
def photo(request, identifier):
recipe = get_object_or_404(_owned(request.user), api_id=identifier)
if not recipe.photo:
from django.http import Http404
raise Http404
file = recipe.photo.open('rb')
image_format = Image.open(file).format
file.seek(0)
response = FileResponse(file, content_type={
'JPEG': 'image/jpeg', 'PNG': 'image/png', 'WEBP': 'image/webp',
}.get(image_format, 'application/octet-stream'))
response['Content-Disposition'] = 'inline'
response['Cache-Control'] = 'private, max-age=3600'
response['X-Content-Type-Options'] = 'nosniff'
return response
+1
View File
@@ -44,6 +44,7 @@ INSTALLED_APPS = [
'oauth2_provider',
'planner',
'food.apps.FoodConfig',
'recipes',
]
MIDDLEWARE = [
+1
View File
@@ -24,5 +24,6 @@ urlpatterns = [
path('api/v1/', include('food.api_urls')),
path('admin/', admin.site.urls),
path('food/', include('food.urls', namespace='food')),
path('recipes/', include('recipes.urls', namespace='recipes')),
path('', include('planner.urls')),
]