1
0
mirror of https://github.com/django/django.git synced 2024-12-23 01:25:58 +00:00

Fixed #34119 -- Prevented callable default hidden widget value from being overridden.

Thanks to Benjamin Rigaud for the report.
This commit is contained in:
David Sanders 2022-10-26 19:05:27 +11:00 committed by Mariusz Felisiak
parent 04b15022e8
commit 25904db915
2 changed files with 49 additions and 1 deletions

View File

@ -96,9 +96,17 @@ class BoundField:
attrs.setdefault(
"id", self.html_initial_id if only_initial else self.auto_id
)
if only_initial and self.html_initial_name in self.form.data:
# Propagate the hidden initial value.
value = self.form._widget_data_value(
self.field.hidden_widget(),
self.html_initial_name,
)
else:
value = self.value()
return widget.render(
name=self.html_initial_name if only_initial else self.html_name,
value=self.value(),
value=value,
attrs=attrs,
renderer=self.form.renderer,
)

View File

@ -203,6 +203,46 @@ class ModelFormCallableModelDefault(TestCase):
""",
)
def test_callable_default_hidden_widget_value_not_overridden(self):
class FieldWithCallableDefaultsModel(models.Model):
int_field = models.IntegerField(default=lambda: 1)
json_field = models.JSONField(default=dict)
class FieldWithCallableDefaultsModelForm(ModelForm):
class Meta:
model = FieldWithCallableDefaultsModel
fields = "__all__"
form = FieldWithCallableDefaultsModelForm(
data={
"initial-int_field": "1",
"int_field": "1000",
"initial-json_field": "{}",
"json_field": '{"key": "val"}',
}
)
form_html = form.as_p()
self.assertHTMLEqual(
form_html,
"""
<p>
<label for="id_int_field">Int field:</label>
<input type="number" name="int_field" value="1000"
required id="id_int_field">
<input type="hidden" name="initial-int_field" value="1"
id="initial-id_int_field">
</p>
<p>
<label for="id_json_field">Json field:</label>
<textarea cols="40" id="id_json_field" name="json_field" required rows="10">
{&quot;key&quot;: &quot;val&quot;}
</textarea>
<input id="initial-id_json_field" name="initial-json_field" type="hidden"
value="{}">
</p>
""",
)
class FormsModelTestCase(TestCase):
def test_unicode_filename(self):