Let the resources search up the stack for views if they don't get one. This lets nested resources access request variables

This commit is contained in:
Adam Ness 2012-06-03 02:07:27 -07:00
parent 4739e1c012
commit db8f0a5395
2 changed files with 13 additions and 3 deletions

View File

@ -15,8 +15,17 @@ class BaseResource(Serializer):
def __init__(self, view=None, depth=None, stack=[], **kwargs):
super(BaseResource, self).__init__(depth, stack, **kwargs)
# If a view is passed, use that. Otherwise traverse up the stack
# to find a view we can use
if view is not None:
self.view = view
self.request = getattr(view, 'request', None)
else:
for serializer in stack[::-1]:
if hasattr(serializer, 'view') \
and getattr(serializer, 'view') != None:
self.view = getattr(serializer, 'view')
break
self.request = getattr(self.view, 'request', None)
def validate_request(self, data, files=None):
"""

View File

@ -100,6 +100,7 @@ class Serializer(object):
def __init__(self, depth=None, stack=[], **kwargs):
if depth is not None:
self.depth = depth
stack.append(self)
self.stack = stack
def get_fields(self, obj):
@ -173,11 +174,11 @@ class Serializer(object):
else:
depth = self.depth - 1
# detect circular references
if any([obj is elem for elem in self.stack]):
return self.serialize_recursion(obj)
else:
stack = self.stack[:]
stack.append(obj)
return related_serializer(depth=depth, stack=stack).serialize(obj)