Skip to content

Instantly share code, notes, and snippets.

@mitchellrj
Created July 25, 2014 08:21
Show Gist options
  • Save mitchellrj/57a3004839d955840a1f to your computer and use it in GitHub Desktop.
Save mitchellrj/57a3004839d955840a1f to your computer and use it in GitHub Desktop.
Tastypie - make fields read only for object update but not for creation
from tastypie.resources import ModelResource as BaseModelResource
class ReadOnlyFieldsAfterAddMeta(BaseModelResource.__metaclass__):
def __new__(cls, name, bases, attrs):
new_class = super(ReadOnlyFieldsAfterAddMeta, cls).__new__(cls, name, bases, attrs)
read_only_fields_after_add = getattr(new_class._meta, 'read_only_after_add', ())
for field_name in read_only_fields_after_add:
# Because scope
def make_hydrator(field_name):
def hydrate_read_only_after_add(self, bundle):
if bundle.obj.pk:
# Rubbish test for newness - but it's the standard way Tastypie does it
if field_name in bundle.data:
del bundle.data[field_name]
return bundle
hydrate_read_only_after_add = make_hydrator(field_name)
method_name = 'hydrate_{0}'.format(field_name)
setattr(new_class, method_name, hydrate_read_only_after_add)
return new_class
class ModelResource(BaseModelResource):
__metaclass__ = ReadOnlyFieldsAfterAddMeta
class MyResource(ModelResource):
class Meta:
queryset = MyModel.objects.all()
read_only_after_add = ('spam', 'ham',)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment