Created
November 27, 2012 18:51
-
-
Save minism/4156216 to your computer and use it in GitHub Desktop.
Tastypie ModelForm validation that only validates submitted fields on PUT requests
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
from tastypie.validation import CleanedDataFormValidation | |
def pick(d, keys): | |
"""Based on http://underscorejs.org/#pick""" | |
return dict((key, val) for key, val in d.items() if key in keys) | |
class BaseFormValidation(CleanedDataFormValidation): | |
""" | |
Validation logic to use for all resources | |
We ignore errors and cleaned_data on PUT requests for fields not sent | |
This also implements https://github.com/toastdriven/django-tastypie/issues/152 | |
""" | |
def is_valid(self, bundle, request=None): | |
data = bundle.data or {} | |
submitted_fields = data.keys() | |
form = self.form_class(data) | |
if form.is_valid(): | |
# For PUT requests, only select cleaned_data for submitted fields | |
if request and request.method is 'PUT': | |
bundle.data = pick(form.cleaned_data, submitted_fields) | |
else: | |
bundle.data = form.cleaned_data | |
return {} | |
# For PUT requests, only select errors for submitted fields | |
errors = form.errors | |
if request and request.method is 'PUT': | |
errors = pick(form.errors, submitted_fields) | |
return errors | |
# usage | |
from tastypie.resources import ModelResource | |
from .forms import MyModelForm | |
class MyResource(ModelResource): | |
class Meta: | |
validation = BaseFormValidation(form_class=MyModelForm) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment