Created
February 1, 2012 14:33
-
-
Save namsral/1717329 to your computer and use it in GitHub Desktop.
Mixin for the Djando Rest Framework (DFR) to auto-complete objects on creating.
This file contains 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 AutoCompleteResourceMixin(ResourceMixin): | |
def validate_request(self, data, files=None): | |
""" | |
Auto-complete objects when they are created. | |
A REST equivalent to auto-populate for Django web forms. | |
""" | |
method = self.view._method if hasattr(self.view, '_method') else None | |
if 'POST' == method and hasattr(self.model, '_meta'): | |
data_mutable = data.copy() | |
for field in self.model._meta.fields: | |
exclude = tuple(data.keys()) | |
try: | |
exclude += self.form.Meta.exclude | |
except AttributeError: | |
pass | |
if field.name not in exclude and field.has_default(): | |
default = field.get_default() | |
data_mutable.update({field.name:default}) | |
data = data_mutable | |
return self._resource.validate_request(data, files) | |
class MessageResource(AutoCompleteResourceMixin, ModelResource): | |
model = Message |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment