quantity fields in food log and recipe upload drop zone

This commit is contained in:
Joren de Graaf
2026-10-15 20:35:56 +02:00
parent f36f05b9bc
commit 86e3afaca7
25 changed files with 420 additions and 67 deletions
+21 -17
View File
@@ -27,7 +27,7 @@ class RecipeForm(forms.ModelForm):
'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'}),
'photo': forms.FileInput(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'}),
@@ -48,22 +48,7 @@ class RecipeForm(forms.ModelForm):
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
return validate_recipe_photo(photo)
def save(self, commit=True):
recipe = super().save(commit=False)
@@ -73,6 +58,25 @@ class RecipeForm(forms.ModelForm):
return recipe
def validate_recipe_photo(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
class RecipeIngredientForm(forms.ModelForm):
class Meta:
model = RecipeIngredient
@@ -0,0 +1,89 @@
(() => {
const supported = new Set(['image/jpeg', 'image/png', 'image/webp']);
const check = (file, status) => {
if (!file) return false;
if (!supported.has(file.type)) {
status.textContent = 'Choose a JPEG, PNG or WebP image.';
return false;
}
if (file.size > 5 * 1024 * 1024) {
status.textContent = 'Choose an image smaller than 5 MB.';
return false;
}
return true;
};
const drop = (zone, input, onFile) => {
if (!zone || !input) return;
zone.addEventListener('dragover', event => {
if (!Array.from(event.dataTransfer?.types || []).includes('Files')) return;
event.preventDefault();
zone.classList.add('is-dragging');
});
zone.addEventListener('dragleave', () => zone.classList.remove('is-dragging'));
zone.addEventListener('drop', event => {
event.preventDefault();
zone.classList.remove('is-dragging');
if (!event.dataTransfer?.files.length) return;
input.files = event.dataTransfer.files;
onFile();
});
};
const detail = document.querySelector('[data-photo-upload]');
if (detail) {
const input = detail.querySelector('input[type=file]');
const status = detail.querySelector('[data-photo-status]');
const zone = detail.querySelector('.recipes-photo-placeholder');
const submit = detail.querySelector('.recipe-photo-submit');
if (submit) submit.hidden = true;
const upload = () => {
const file = input.files[0];
if (!check(file, status)) return;
status.textContent = `Uploading ${file.name}…`;
detail.requestSubmit();
};
input.addEventListener('change', upload);
drop(zone, input, upload);
}
const editor = document.querySelector('[data-photo-editor]');
if (editor) {
const input = editor.querySelector('input[type=file]');
const zone = editor.querySelector('.recipe-photo-editor__zone');
const preview = editor.querySelector('[data-photo-preview]');
const prompt = editor.querySelector('[data-photo-prompt]');
const remove = editor.querySelector('[data-photo-remove]');
const checkbox = editor.parentElement.querySelector('input[name=remove_photo]');
const status = editor.parentElement.querySelector('[data-photo-edit-status]');
const hasPhoto = !preview.hidden;
let previewUrl;
const selected = () => {
const file = input.files[0];
if (!file) return;
if (!check(file, status)) { input.value = ''; return; }
if (previewUrl) URL.revokeObjectURL(previewUrl);
previewUrl = URL.createObjectURL(file);
preview.src = previewUrl;
preview.hidden = false;
checkbox.checked = false;
remove.hidden = false;
prompt.firstChild.textContent = 'Click or drop to change photo';
status.textContent = `${file.name} selected. Save the recipe to upload it.`;
};
input.addEventListener('change', selected);
drop(zone, input, () => input.dispatchEvent(new Event('change', {bubbles: true})));
remove.addEventListener('click', () => {
input.value = '';
if (previewUrl) URL.revokeObjectURL(previewUrl);
previewUrl = null;
preview.removeAttribute('src');
preview.hidden = true;
checkbox.checked = hasPhoto;
remove.hidden = true;
prompt.firstChild.textContent = 'Click or drop a photo here';
status.textContent = hasPhoto ? 'Current photo will be removed when you save.' : 'Selected photo cleared.';
checkbox.dispatchEvent(new Event('change', {bubbles: true}));
input.focus();
});
}
})();
+6
View File
@@ -40,3 +40,9 @@ body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI,body[da
.recipes-saved-badge{align-self:center;padding:5px 8px;border-radius:99px;background:#e1f2e8;color:#235943;font-size:.72rem;font-weight:700}
.cook-later{max-width:850px;margin:0 auto;padding:20px;color:var(--recipe-ink,#25292e)}.cook-later h1{margin:15px 0 5px;font-family:Fraunces,Georgia,serif}.cook-later__list{display:grid;gap:12px;margin-top:24px}.cook-later__item{display:flex;align-items:center;justify-content:space-between;gap:20px;padding:18px;border:1px solid var(--recipe-line,#d0d8d0);border-radius:14px;background:var(--recipe-surface,#fff)}.cook-later__item h2{margin:0;font-size:1.15rem}.cook-later__item p{margin:6px 0}.cook-later__item small{color:var(--recipe-muted,#687178)}.cook-later__item button{min-height:44px;padding:8px 14px;border:1px solid #b94a55;border-radius:9px;background:transparent;color:#a12435;cursor:pointer}body[data-theme=dark] .cook-later__item button{color:#ffb3bb}body[data-theme=dark] .recipes-saved-badge{background:#294d38;color:#b7e8c5}@media(max-width:600px){.cook-later__item{align-items:flex-start;flex-direction:column}}
body[data-theme=dark] .cook-later{--recipe-ink:#eaf0ea;--recipe-muted:#afbbb2;--recipe-surface:#202a23;--recipe-line:#435046}body[data-theme=dark] .cook-later a{color:#a7d9b6}
/* Recipe photo upload controls */
.recipe-photo-upload{min-width:0}.recipe-photo-upload .recipes-photo-placeholder{position:relative;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:7px;height:220px;padding:20px;border:2px dashed #719d7d;border-radius:14px;color:#24573b;background:#e5f1e8;text-align:center;cursor:pointer;font-family:inherit;transition:border-color .15s,background .15s}.recipe-photo-upload__icon{display:grid;place-items:center;width:42px;height:42px;border-radius:50%;background:#d0e6d6;font-size:1.5rem;font-weight:700}.recipe-photo-upload .recipes-photo-placeholder strong{font-size:1rem}.recipe-photo-upload .recipes-photo-placeholder span:last-of-type{max-width:220px;font-size:.77rem;line-height:1.4}.recipe-photo-upload .recipes-photo-placeholder:hover,.recipe-photo-upload .recipes-photo-placeholder.is-dragging{border-color:#235943;background:#d9ebdf}.recipe-photo-upload .recipes-photo-placeholder:focus-within,.recipe-photo-editor__zone:focus-within{outline:3px solid #a44cbe;outline-offset:3px}.recipe-photo-upload input[type=file],.recipe-photo-editor input[type=file]{position:absolute;width:1px;height:1px;opacity:0;overflow:hidden}.recipe-photo-submit{margin-top:8px;min-height:40px;padding:7px 12px;border:0;border-radius:8px;color:#fff;background:#235943;cursor:pointer}.recipe-photo-submit[hidden]{display:none}.recipe-photo-upload__status{display:block;margin-top:6px;color:var(--recipe-muted);font-size:.75rem}
.recipes-photo-field-label{display:block;margin-bottom:6px;font-size:.81rem;font-weight:700}.recipe-photo-editor{position:relative;max-width:490px}.recipe-photo-editor__zone{position:relative;display:grid;place-items:center;min-height:225px;overflow:hidden;border:2px dashed #719d7d;border-radius:14px;background:#e5f1e8;color:#24573b;text-align:center;cursor:pointer}.recipe-photo-editor__zone.is-dragging,.recipe-photo-editor__zone:hover{border-color:#235943;background:#d9ebdf}.recipe-photo-editor__zone img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}.recipe-photo-editor__zone img[hidden]{display:none}.recipe-photo-editor__prompt{z-index:1;max-width:260px;padding:10px 16px;border-radius:10px;background:rgba(255,255,255,.88);font-size:.9rem;font-weight:700}.recipe-photo-editor__prompt small{display:block;margin-top:4px;font-weight:400}.recipe-photo-editor__remove{position:absolute;z-index:2;top:10px;right:10px;display:grid;place-items:center;width:36px;height:36px;border:0;border-radius:50%;color:#fff;background:#223029;font-size:1.45rem;line-height:1;cursor:pointer}.recipe-photo-editor__remove[hidden]{display:none}.recipe-photo-editor__remove:focus-visible{outline:3px solid #a44cbe;outline-offset:3px}.recipe-photo-editor__status{min-height:1.2em;margin:7px 0 0;color:var(--recipe-muted);font-size:.78rem}.recipe-photo-editor__checkbox[hidden]{display:none}body[data-theme=dark] .recipe-photo-upload .recipes-photo-placeholder,body[data-theme=dark] .recipe-photo-editor__zone{color:#c7e8cf;background:#314d39;border-color:#79a889}body[data-theme=dark] .recipe-photo-upload .recipes-photo-placeholder:hover,body[data-theme=dark] .recipe-photo-editor__zone:hover,body[data-theme=dark] .recipe-photo-editor__zone.is-dragging{background:#3a6246}body[data-theme=dark] .recipe-photo-upload__icon{background:#446f50}body[data-theme=dark] .recipe-photo-editor__prompt{color:#24372a}
.recipes-field .recipe-photo-editor__zone{display:grid;margin:0;align-items:center;justify-items:center}
.recipes-field label.recipe-photo-editor__zone{display:grid;margin:0;align-items:center;justify-items:center}
.recipe-photo-editor__prompt small,body[data-theme=dark] .recipe-photo-editor__prompt small{color:#415c4b}
+3 -3
View File
@@ -1,13 +1,13 @@
{% 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/vendor/toastui-editor.min.css' %}"><link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=4">
{% block content %}<link rel="stylesheet" href="{% static 'recipes/vendor/toastui-editor.min.css' %}"><link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=11">
<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 data-autosave-url="{% if creating %}{% url 'recipes:autosave-new' %}{% else %}{% url 'recipes:autosave' recipe.api_id %}{% endif %}"{% if creating %} data-draft-id="{{ new_draft_id }}"{% endif %}>{% csrf_token %}
{% if creating %}<input type="hidden" name="draft_id" value="{{ new_draft_id }}">{% endif %}
{% 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 == 'markdown_revision' %}{{ field }}{% elif field.name != 'remove_photo' %}<div class="recipes-field recipes-field--{{ field.name }}"><label for="{{ field.id_for_label }}">{{ field.label }}</label>{{ field }}{% if field.name == 'instructions_markdown' or field.name == 'notes_markdown' %}<div class="recipes-markdown-editor" data-markdown-editor="{{ field.name }}" aria-label="{{ field.label }} editor"></div>{% endif %}{% 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><h2>Recipe details</h2><div class="recipes-form-grid">{% for field in form %}{% if field.name == 'markdown_revision' %}{{ field }}{% elif field.name == 'photo' %}<div class="recipes-field recipes-field--photo"><span class="recipes-photo-field-label">Recipe photo</span><div class="recipe-photo-editor" data-photo-editor><label class="recipe-photo-editor__zone" for="{{ field.id_for_label }}">{% if existing_photo %}<img src="{% url 'recipes:photo' recipe.api_id %}" alt="Current recipe photo" data-photo-preview>{% else %}<img alt="Selected recipe photo preview" data-photo-preview hidden>{% endif %}<span class="recipe-photo-editor__prompt" data-photo-prompt>{% if existing_photo %}Click or drop to replace photo{% else %}Click or drop a photo here{% endif %}<small>JPEG, PNG or WebP · up to 5 MB</small></span>{{ field }}</label><button type="button" class="recipe-photo-editor__remove" data-photo-remove aria-label="Remove current recipe photo"{% if not existing_photo %} hidden{% endif %}>×</button></div><label class="recipes-checkbox recipe-photo-editor__checkbox" hidden>{{ form.remove_photo }} Remove current photo on save</label><p class="recipe-photo-editor__status" data-photo-edit-status role="status" aria-live="polite"></p>{% if field.errors %}<div class="recipes-form-error" role="alert">{{ field.errors }}</div>{% endif %}</div>{% elif field.name != 'remove_photo' %}<div class="recipes-field recipes-field--{{ field.name }}"><label for="{{ field.id_for_label }}">{{ field.label }}</label>{{ field }}{% if field.name == 'instructions_markdown' or field.name == 'notes_markdown' %}<div class="recipes-markdown-editor" data-markdown-editor="{{ field.name }}" aria-label="{{ field.label }} editor"></div>{% endif %}{% 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 %}</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>
<section><div class="recipes-section-heading"><div><h2>Subrecipes</h2><p>Include an independently editable recipe as a component.</p></div><button type="button" class="recipes-outline-button" data-add-subrecipe>+ Add subrecipe</button></div>{{ subrecipes.management_form }}{% if subrecipes.non_form_errors %}<div class="recipes-form-error" role="alert">{{ subrecipes.non_form_errors }}</div>{% endif %}<div class="recipes-ingredient-forms" data-subrecipe-forms>{% for subrecipe in subrecipes %}{% include 'recipes/subrecipe_row.html' %}{% endfor %}</div><template id="recipe-empty-subrecipe">{% with subrecipe=subrecipes.empty_form %}{% include 'recipes/subrecipe_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><span class="recipes-save-status" data-save-status role="status" aria-live="polite">{% if creating %}Add a title to start autosave.{% else %}Saved{% endif %}</span></div>
</form></div><script defer src="{% static 'recipes/vendor/toastui-editor-all.min.js' %}"></script><script defer src="{% static 'recipes/editor-adapter.js' %}?v=4"></script><script defer src="{% static 'recipes/form.js' %}?v=5"></script>{% endblock %}
</form></div><script defer src="{% static 'recipes/vendor/toastui-editor-all.min.js' %}"></script><script defer src="{% static 'recipes/editor-adapter.js' %}?v=4"></script><script defer src="{% static 'recipes/form.js' %}?v=6"></script><script defer src="{% static 'recipes/photo_upload.js' %}?v=1"></script>{% endblock %}
+3 -3
View File
@@ -2,7 +2,7 @@
{% block title %}Recipes · Tasknest{% endblock %}
{% block page_class %}recipes-page-content{% endblock %}
{% block content %}
<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=7">
<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=8">
<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">
@@ -40,7 +40,7 @@
{% 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 %}
{% if selected.photo %}<img src="{% url 'recipes:photo' selected.api_id %}" alt="Photo of {{ selected.title }}">{% else %}<form class="recipe-photo-upload" method="post" enctype="multipart/form-data" action="{% url 'recipes:photo-upload' selected.api_id %}" data-photo-upload>{% csrf_token %}<label class="recipes-photo-placeholder" for="recipe-detail-photo"><span class="recipe-photo-upload__icon" aria-hidden="true">↑</span><strong>Add a recipe photo</strong><span>Click or drop a JPEG, PNG or WebP image</span><input id="recipe-detail-photo" name="photo" type="file" accept="image/jpeg,image/png,image/webp" required></label><button class="recipe-photo-submit" type="submit">Upload photo</button><span class="recipe-photo-upload__status" data-photo-status role="status" aria-live="polite"></span></form>{% 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>
<form class="recipes-serving-form" method="get" action="{% url 'recipes:detail' selected.api_id %}"><label for="recipe-servings">Servings</label><input id="recipe-servings" type="number" name="servings" min="0.01" max="99999.99" step="0.01" value="{{ analysis.servings|floatformat:-2 }}"><label class="recipes-checkbox"><input type="checkbox" name="optional" value="1"{% if analysis.include_optional %} checked{% endif %}> Include optional ingredients</label><button type="submit" class="recipes-outline-button">Update</button></form>
@@ -63,5 +63,5 @@
<section class="recipes-panel"><h3>Actions</h3><a class="recipes-action" href="{% url 'recipes:edit' selected.api_id %}">Edit recipe</a><form method="post" action="{% url 'recipes:create-variation' selected.api_id %}" class="recipes-action-form">{% csrf_token %}<button type="submit" class="recipes-action">Create variation</button></form>{% if last_use %}<form method="post" action="{% url 'recipes:stock-undo' last_use.pk %}" class="recipes-action-form">{% csrf_token %}<button type="submit" class="recipes-action">Undo last inventory use</button></form>{% endif %}<a class="recipes-action recipes-action--danger" href="{% url 'recipes:delete' selected.api_id %}">Delete recipe</a></section>
</aside>{% endif %}
</div>
<script src="{% static 'planner/responsive_filters.js' %}?v=1" defer></script>
<script src="{% static 'planner/responsive_filters.js' %}?v=1" defer></script><script src="{% static 'recipes/photo_upload.js' %}?v=1" defer></script>
{% endblock %}
+24
View File
@@ -99,6 +99,30 @@ class RecipeWebTests(TestCase):
self.client.force_login(self.other)
self.assertEqual(self.client.get(photo_url).status_code, 404)
def test_detail_photo_drop_zone_upload_validates_and_scopes(self):
recipe = Recipe.objects.create(owner=self.user, title='Photo target')
image = BytesIO()
Image.new('RGB', (2, 2), '#217857').save(image, format='PNG')
url = reverse('recipes:photo-upload', args=[recipe.api_id])
with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
self.assertContains(self.client.get(reverse('recipes:detail', args=[recipe.api_id])),
'Add a recipe photo')
self.assertEqual(self.client.get(url).status_code, 405)
self.assertEqual(self.client.post(url, {'photo': SimpleUploadedFile(
'bad.png', b'not an image', content_type='image/png')}).status_code, 302)
recipe.refresh_from_db()
self.assertFalse(recipe.photo)
response = self.client.post(url, {'photo': SimpleUploadedFile(
'good.png', image.getvalue(), content_type='image/png')})
self.assertEqual(response.status_code, 302)
recipe.refresh_from_db()
self.assertTrue(recipe.photo)
self.assertContains(self.client.get(reverse('recipes:detail', args=[recipe.api_id])),
'Photo of Photo target')
self.client.force_login(self.other)
self.assertEqual(self.client.post(url, {'photo': SimpleUploadedFile(
'other.png', image.getvalue(), content_type='image/png')}).status_code, 404)
def test_markdown_round_trip_and_safe_rendering(self):
source = '# Dinner\n\n- [x] Prepare\n- [ ] Cook\n\n**Ready** <script>alert(1)</script> [bad](javascript:alert(1))'
recipe = Recipe.objects.create(owner=self.user, title='Dinner', instructions_markdown=source)
+1
View File
@@ -17,6 +17,7 @@ urlpatterns = [
path('new/autosave/', views.autosave_new, name='autosave-new'),
path('<uuid:identifier>/', views.detail, name='detail'),
path('<uuid:identifier>/edit/', views.edit, name='edit'),
path('<uuid:identifier>/photo/upload/', views.photo_upload, name='photo-upload'),
path('<uuid:identifier>/cook/', views.cook, name='cook'),
path('<uuid:identifier>/cook/finish/', views.cook_finish, name='cook-finish'),
path('<uuid:identifier>/autosave/', views.autosave, name='autosave'),
+26 -1
View File
@@ -2,6 +2,7 @@ import json
import uuid
from django.conf import settings
from django.core.exceptions import ValidationError
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
@@ -17,7 +18,7 @@ from food.models import MealType
from PIL import Image
from .forms import (RecipeForm, RecipeIngredientFormSet, RecipeSubrecipeFormSet,
RecipeSubstitutionForm)
RecipeSubstitutionForm, validate_recipe_photo)
from .models import (CookLater, Recipe, RecipeIngredient, RecipeIngredientSubstitution,
RecipeSelection, RecipeSubrecipe, RecipeUse)
from .services import cook_later
@@ -364,6 +365,7 @@ def _edit(request, recipe=None, allow_draft_resume=False):
return render(request, 'recipes/form.html', {
'form': form, 'ingredients': ingredients, 'subrecipes': subrecipes, 'recipe': recipe,
'creating': creating, 'new_draft_id': recipe.api_id if creating else None,
'existing_photo': bool(old_photo),
})
@@ -389,6 +391,29 @@ def edit(request, identifier):
return _edit(request, get_object_or_404(_owned(request.user), api_id=identifier))
@login_required
@require_POST
def photo_upload(request, identifier):
recipe = get_object_or_404(_owned(request.user), api_id=identifier)
uploaded = request.FILES.get('photo')
if uploaded is None:
messages.error(request, 'Choose a photo to upload.')
return redirect('recipes:detail', identifier=identifier)
try:
validate_recipe_photo(uploaded)
except ValidationError as exc:
messages.error(request, exc.messages[0])
return redirect('recipes:detail', identifier=identifier)
old_name = recipe.photo.name if recipe.photo else ''
storage = recipe.photo.storage
recipe.photo = uploaded
recipe.save(update_fields=('photo', 'updated_at'))
if old_name and old_name != recipe.photo.name:
transaction.on_commit(lambda: storage.delete(old_name))
messages.success(request, 'Recipe photo uploaded.')
return redirect('recipes:detail', identifier=identifier)
@login_required
@require_POST
def autosave(request, identifier):