Last active
May 28, 2018 08:18
-
-
Save jbbarth/bd93b4d78b5b7f3d6a375505cf77b030 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PirateForm(ModelForm): | |
class Meta: | |
model = Pirate | |
fields = ("name", "is_captain") | |
def __init__(self, *args, **kwargs): | |
super().__init__(*args, **kwargs) | |
self.cleanup_missing_keys(kwargs.get("data")) | |
def cleanup_missing_keys(self, data): | |
""" | |
Removes missing keys from fields on form submission. | |
This avoids resetting fields that are not present in | |
the submitted data, which may be the sign of a buggy | |
or incomplete template. | |
Note that this cleanup relies on the HTML form being | |
patched to send all keys, even for checkboxes, via | |
input[type="hidden"] fields or some JS magic. | |
""" | |
if data is None: | |
# not a form submission, don't modify self.fields | |
return | |
got_keys = data.keys() | |
field_names = self.fields.keys() | |
for missing in set(field_names) - set(got_keys): | |
del self.fields[missing] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment