Skip to content

Commit

Permalink
Fixed #34119 -- Prevented callable default hidden widget value from b…
Browse files Browse the repository at this point in the history
…eing overridden.

Thanks to Benjamin Rigaud for the report.
  • Loading branch information
shangxiao authored and felixxm committed Nov 18, 2022
1 parent 04b1502 commit 25904db
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
10 changes: 9 additions & 1 deletion django/forms/boundfield.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,17 @@ def as_widget(self, widget=None, attrs=None, only_initial=False):
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,
)
Expand Down
40 changes: 40 additions & 0 deletions tests/forms_tests/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,46 @@ def test_initial_instance_value(self):
""",
)

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):
Expand Down

0 comments on commit 25904db

Please sign in to comment.