Repository: marshmallow-code/marshmallow

Issue:
Question: How can I pass the context in a nested field of a structured dict?
I noticed that if you use a nested field for values in a structured Dict, the context is not automatically given to the nested schema. Is there a way to pass it the context?

Example:
```python
class Inner(Schema):
    foo = fields.String()

    @validates('foo')
    def validate_foo(self, value):
        if 'foo_context' not in self.context:
            raise ValidationError('no context!')


class Outer(Schema):
    bar = fields.Dict(values=fields.Nested(Inner))

# gives no error:
Inner(context={'foo_context': 'foo'}).load({'foo': 'some foo'})
# gives 'no context!' error:
Outer(context={'foo_context': 'foo'}).load({'bar': { 'key': {'foo': 'some foo'}}})
```

Discussion:

Patch:
diff --git a/marshmallow/fields.py b/marshmallow/fields.py
index ecfd28d4..737fbfb0 100755
--- a/marshmallow/fields.py
+++ b/marshmallow/fields.py
@@ -1134,6 +1134,15 @@ class Dict(Field):
                                  'marshmallow.base.FieldABC')
             self.key_container = keys
 
+    def _add_to_schema(self, field_name, schema):
+        super(Dict, self)._add_to_schema(field_name, schema)
+        if self.value_container:
+            self.value_container.parent = self
+            self.value_container.name = field_name
+        if self.key_container:
+            self.key_container.parent = self
+            self.key_container.name = field_name
+
     def _serialize(self, value, attr, obj):
         if value is None:
             return None


Test patch:
diff --git a/tests/test_schema.py b/tests/test_schema.py
index 17c04300..9fee0d63 100755
--- a/tests/test_schema.py
+++ b/tests/test_schema.py
@@ -2134,6 +2134,27 @@ class TestContext:
         outer.context['foo_context'] = 'foo'
         assert outer.load({'bars': [{'foo': 42}]})
 
+    # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820
+    def test_nested_dict_fields_inherit_context(self):
+        class InnerSchema(Schema):
+            foo = fields.Field()
+
+            @validates('foo')
+            def validate_foo(self, value):
+                if 'foo_context' not in self.context:
+                    raise ValidationError('Missing context')
+
+        class OuterSchema(Schema):
+            bars = fields.Dict(values=fields.Nested(InnerSchema()))
+
+        inner = InnerSchema()
+        inner.context['foo_context'] = 'foo'
+        assert inner.load({'foo': 42})
+
+        outer = OuterSchema()
+        outer.context['foo_context'] = 'foo'
+        assert outer.load({'bars': {'test': {'foo': 42}}})
+
 
 def test_serializer_can_specify_nested_object_as_attribute(blog):
     class BlogUsernameSchema(Schema):