Skip to content

Instantly share code, notes, and snippets.

@minism
Created November 27, 2012 18:51
Show Gist options
  • Save minism/4156216 to your computer and use it in GitHub Desktop.
Save minism/4156216 to your computer and use it in GitHub Desktop.
Tastypie ModelForm validation that only validates submitted fields on PUT requests
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