Created
March 13, 2013 01:28
-
-
Save yuchant/5148674 to your computer and use it in GitHub Desktop.
Django ModelForm Mixin to prevent overwriting of data if the form does not contain the POST keys
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
from django.forms.models import model_to_dict | |
from django import forms | |
class OverwriteOnlyModelFormMixin(object): | |
''' | |
Delete POST keys that were not actually found in the POST dict | |
to prevent accidental overwriting of fields due to missing POST data. | |
''' | |
def clean(self): | |
cleaned_data = super(OverwriteOnlyModelFormMixin, self).clean() | |
for field in cleaned_data.keys(): | |
if self.prefix is not None: | |
post_key = '-'.join((self.prefix, field)) | |
else: | |
post_key = field | |
if post_key not in self.data: | |
# value was not posted, thus it should not overwrite any data. | |
del cleaned_data[field] | |
# only overwrite keys that were actually submitted via POST. | |
model_data = model_to_dict(self.instance) | |
model_data.update(cleaned_data) | |
return model_data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment