Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make a tastypie modelresource field read-only?

Tags:

tastypie

I have a Tastypie ModelResource which gets its fields from a regular Django Model. I would like to make certain fields read-only on the Tastypie resource, even though they are writeable in the underlying model. Is this possible to accomplish in a simple way?

I've tried the following to no avail:

def __init__(self, **kwargs):
    super(ModelResource, self).__init__(**kwargs)
    for f in getattr(self.Meta, 'read_onlys', []):
        self.fields[f].read_only = True
like image 558
Matti Kotsalainen Avatar asked Apr 27 '12 17:04

Matti Kotsalainen


1 Answers

Normally I would do that sort of thing in the hydrate/dehydrate process.

There are probably other ways,

def hydrate(self, bundle):
    if bundle.obj.pk:
        bundle.data['somefield'] = bundle.obj.somefield
    else:
        bundle.data.pop('somefield', None)  # no KeyError if 'somefield' missing

    return super(MyResource, self).hydrate(bundle)
like image 95
Issac Kelly Avatar answered Sep 29 '22 21:09

Issac Kelly