Created
July 25, 2014 08:21
-
-
Save mitchellrj/57a3004839d955840a1f to your computer and use it in GitHub Desktop.
Tastypie - make fields read only for object update but not for creation
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.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