Can I make a tastypie modelresource field read-only?
Asked Answered
I

3

11

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
Inanna answered 27/4, 2012 at 17:11 Comment(6)
Sorry, I forgot to mention that I couldn't get the aforementioned 'hack' to work with the resource/schema that is generated by Tastypie, which is really what I'm afterInanna
Ooops. I got it work by changing read_only to readonly. My bad.Inanna
shouldn't the super call have your classname in itLehmann
tolomea: you're right. I've made this mistake before. I wish there was a simpler / shorter way to to call the superclass without using super(MyClass, self) or SuperClass.foo(self).Inanna
Wait for python 3, super will magically be smart about the calling class and instance. docs.python.org/3.1/library/functions.html#superDebouch
It would be nice if this was added to Tastypie. I would rename 'read_onlys' to 'readonly_fields' though.Camelot
A
4

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)
Archenemy answered 2/5, 2012 at 3:53 Comment(1)
You're right, but I forgot to mention that I wanted the schema that Tastypie can output for the resource to refelect that it was readonly. My 'solution' does this for me.Inanna
A
0

The problem is that BaseModelForm overwrites self.instance when doing validation.

And this ofcourse happens regardless if a Tastypie field has readonly set or not (that onfly affects Tastypie's own hydrate, nothing else).

So I ended up writing this: https://gist.github.com/thnee/8522224

Atheistic answered 20/1, 2014 at 15:41 Comment(0)
F
0

Not sure whether you need this anymore, but here's the link to official documentation related to readonly fields.

example:

class ResourceA(ModelResource):
    read_only_field = fields.DateTimeField('attribute', readonly=True)

Hope this helps someone.

Thanks

Felicitation answered 17/12, 2014 at 10:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.