From d4f1862f365d68b24f4a1bfdad917baf3b715b8f Mon Sep 17 00:00:00 2001
From: Christoph Berg <myon@debian.org>
Date: Wed, 29 Jul 2026 12:00:05 +0000
Subject: [PATCH v7 2/5] Rewind uploaded file before reading in
 ImageBinaryFormField

to_python() read the UploadedFile without seeking to 0 first. Since the
field extends forms.Field, has_changed()/changed_data or a repeated
full_clean() can trigger a second read() that returns b'' (pointer at
EOF), silently saving an empty image. Seek before reading to make the
field robust regardless of form flow.

The current speaker forms happen to validate only once and never touch
changed_data, so this is latent rather than an active bug here.

Discovered while porting the ImageBinaryField machinery to pgweb.
---
 pgweb/util/forms.py | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/pgweb/util/forms.py b/pgweb/util/forms.py
index 2d885809..790ab677 100644
--- a/pgweb/util/forms.py
+++ b/pgweb/util/forms.py
@@ -16,6 +16,12 @@ class ImageBinaryFormField(forms.Field):
             return None
         if value is None:
             return None
+        # value is an UploadedFile. to_python() can run more than once per
+        # request (e.g. Field.has_changed() -> changed_data, or a second
+        # full_clean()), so rewind before reading to avoid returning b'' on a
+        # subsequent pass.
+        if hasattr(value, 'seek'):
+            value.seek(0)
         return value.read()
 
     def prepare_value(self, value):
-- 
2.53.0

