We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
akvo.rest.fields in from_native AttributeError: 'NoneType' object has no attribute 'name'
http://sentry.support.akvo-ops.org/rsr/live/group/1017/

Bug introduced in 1aa60508350d4477c1f0964db7f3c124d9d1bc01

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `akvo/rest/fields.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 # Akvo RSR is covered by the GNU Affero General Public License.
4 # See more details in the license.txt file located at the root folder of the Akvo RSR module.
5 # For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
6 
7 
8 import base64
9 import imghdr
10 import six
11 import uuid
12 
13 from django.core.files.base import ContentFile
14 from django.utils.encoding import smart_text
15 from django.utils.translation import ugettext_lazy as _
16 
17 from rest_framework import serializers
18 from rest_framework.fields import ImageField
19 from sorl.thumbnail import get_thumbnail
20 from sorl.thumbnail.parsers import ThumbnailParseError
21 
22 
23 class NonNullCharField(serializers.CharField):
24     """ Fix fo CharField so that '' is returned if the field value is None
25         see https://github.com/tomchristie/django-rest-framework/pull/1665
26     """
27     def from_native(self, value):
28         if isinstance(value, six.string_types):
29             return value
30         if value is None:
31             return u''
32         return smart_text(value)
33 
34 
35 class NonNullURLField(NonNullCharField, serializers.URLField):
36     pass
37 
38 
39 class Base64ImageField(ImageField):
40     """ A django-rest-framework field for handling image-uploads through raw post data.
41         It uses base64 for en-/decoding the contents of the file.
42         Now also supports thumbnails of different sizes. See to_native() for more info.
43     """
44     ALLOWED_IMAGE_TYPES = (
45         'gif',
46         'jpeg',
47         'jpg',
48         'png',
49     )
50     def from_native(self, base64_data):
51         # Check if this is a base64 string
52         if isinstance(base64_data, basestring):
53             # Try to decode the file. Return validation error if it fails.
54             try:
55                 decoded_file = base64.b64decode(base64_data)
56             except TypeError:
57                 raise serializers.ValidationError(_(u"Please upload a valid image."))
58 
59             # Generate file name:
60             file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.
61             # Get the file name extension:
62             file_extension = self.get_file_extension(file_name, decoded_file)
63             self.check_file_extension(file_extension)
64             complete_file_name = file_name + "." + file_extension
65             data = ContentFile(decoded_file, name=complete_file_name)
66         else:
67             data = base64_data
68             file_extension = self.get_file_extension(data.name, data.read())
69             self.check_file_extension(file_extension)
70             data.seek(0)
71 
72         return super(Base64ImageField, self).from_native(data)
73 
74     def to_native(self, value):
75         """
76         :param value: A Base64ImageField object
77         :return: a path to a thumbnail with a predetermined size, the default thumb
78         OR
79         a dict with a number of thumbnails, one of which is the default, the others being generated
80         from the query string parameters, and finally the path to the original image keyed to
81         "original".
82 
83         The extended functionality, allowing the generation of one or more thumbnails from the
84         original image is triggered by including "image_thumb_name" in the query string. The value
85         for image_thumb_name is a comma separated list of identifiers for the generated thumbs.
86         The names must not be "default" or "original".
87 
88         For each thumb thus specified a size must be supplied as a query param on the form
89             image_thumb_<name>_<dimension>
90         where <name> is the name of the thumb specified as one of the values for image_thumb_name
91         and <dimension> is one of "width, "height" or "max_size". width and height must be an integer
92         specifying that dimension in pixels. The image will be scaled correctly in the other
93         dimension. max_size is width and height concatenated with an "x" and sets the maximum size
94         allowed for the respective dimensions, while still maintaining the correct aspect ratio of
95         the image.
96 
97         Example:
98         the querystring
99             ?image_thumb_name=big,small&image_thumb_small_width=90&image_thumb_big_max_size=300x200
100         results in the following dict being returned:
101         {
102             'original': '/full/path/to/original/image.png',
103             'default': '/full/path/to/default/thumbnail/image.png',
104             'small': '/full/path/to/small/thumbnail/image.png',
105             'big': '/full/path/to/big/thumbnail/image.png',
106         }
107         This dict will be converted as appropriate to JSON or XML
108 
109         NOTE: This special functionality works best when there is only one image field in a model.
110         If there are more, things will still work (I think), but for each image all thumbs returned
111         will have the same dimensions
112         """
113         def get_thumb(request, name):
114             if name not in [u'original', u'default']:
115                 try:
116                     width = request.GET.get('image_thumb_{}_width'.format(name))
117                     if width:
118                         return get_thumbnail(value, '{}'.format(width), quality=99)
119                     height = request.GET.get('image_thumb_{}_height'.format(name))
120                     if height:
121                         return get_thumbnail(value, 'x{}'.format(height), quality=99)
122                     # yes this is redundant...code is nearly identical with the width code above
123                     # but for clarity of function we keep them separate
124                     max_size = request.GET.get('image_thumb_{}_max_size'.format(name))
125                     if max_size:
126                         return get_thumbnail(value, '{}'.format(max_size), quality=99)
127                 except (ThumbnailParseError, IOError):
128                     return None
129 
130             # no size specification matching the name found; give up
131             return None
132 
133         if value:
134             default_width = '191' # width of update images on akvo.org/seeithappen
135             try:
136                 default_thumb = get_thumbnail(value, default_width, quality=99)
137                 request = self.context['request']
138             except (ThumbnailParseError, IOError, KeyError):
139                 return None
140 
141             # look for name(s) of thumb(s)
142             image_thumb_name = request.GET.get('image_thumb_name')
143             if image_thumb_name:
144                 names = image_thumb_name.split(',')
145                 thumbs = {u'original': value.url, u'default': default_thumb.url}
146                 for name in names:
147                     thumb = get_thumb(request, name)
148                     if thumb is not None:
149                         thumbs[name] = thumb.url
150                 return thumbs
151             return default_thumb.url
152 
153     def get_file_extension(self, filename, decoded_file):
154         extension = imghdr.what(filename, decoded_file)
155         extension = "jpg" if extension == "jpeg" else extension
156         return extension
157 
158     def check_file_extension(self, file_extension):
159         if file_extension not in self.ALLOWED_IMAGE_TYPES:
160             formats = {'format': ', '.join(self.ALLOWED_IMAGE_TYPES)}
161             raise serializers.ValidationError(
162                 _(u"Unknown image type. Only the following types are accepted: %(format)s") % formats
163             )
164
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/akvo/rest/fields.py b/akvo/rest/fields.py
--- a/akvo/rest/fields.py
+++ b/akvo/rest/fields.py
@@ -48,8 +48,10 @@
         'png',
     )
     def from_native(self, base64_data):
+        if base64_data is None:
+            data = base64_data
         # Check if this is a base64 string
-        if isinstance(base64_data, basestring):
+        elif isinstance(base64_data, basestring):
             # Try to decode the file. Return validation error if it fails.
             try:
                 decoded_file = base64.b64decode(base64_data)

{"golden_diff": "diff --git a/akvo/rest/fields.py b/akvo/rest/fields.py\n--- a/akvo/rest/fields.py\n+++ b/akvo/rest/fields.py\n@@ -48,8 +48,10 @@\n         'png',\n     )\n     def from_native(self, base64_data):\n+        if base64_data is None:\n+            data = base64_data\n         # Check if this is a base64 string\n-        if isinstance(base64_data, basestring):\n+        elif isinstance(base64_data, basestring):\n             # Try to decode the file. Return validation error if it fails.\n             try:\n                 decoded_file = base64.b64decode(base64_data)\n", "issue": "akvo.rest.fields in from_native AttributeError: 'NoneType' object has no attribute 'name'\nhttp://sentry.support.akvo-ops.org/rsr/live/group/1017/\n\nBug introduced in 1aa60508350d4477c1f0964db7f3c124d9d1bc01\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Akvo RSR is covered by the GNU Affero General Public License.\n# See more details in the license.txt file located at the root folder of the Akvo RSR module.\n# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.\n\n\nimport base64\nimport imghdr\nimport six\nimport uuid\n\nfrom django.core.files.base import ContentFile\nfrom django.utils.encoding import smart_text\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom rest_framework import serializers\nfrom rest_framework.fields import ImageField\nfrom sorl.thumbnail import get_thumbnail\nfrom sorl.thumbnail.parsers import ThumbnailParseError\n\n\nclass NonNullCharField(serializers.CharField):\n    \"\"\" Fix fo CharField so that '' is returned if the field value is None\n        see https://github.com/tomchristie/django-rest-framework/pull/1665\n    \"\"\"\n    def from_native(self, value):\n        if isinstance(value, six.string_types):\n            return value\n        if value is None:\n            return u''\n        return smart_text(value)\n\n\nclass NonNullURLField(NonNullCharField, serializers.URLField):\n    pass\n\n\nclass Base64ImageField(ImageField):\n    \"\"\" A django-rest-framework field for handling image-uploads through raw post data.\n        It uses base64 for en-/decoding the contents of the file.\n        Now also supports thumbnails of different sizes. See to_native() for more info.\n    \"\"\"\n    ALLOWED_IMAGE_TYPES = (\n        'gif',\n        'jpeg',\n        'jpg',\n        'png',\n    )\n    def from_native(self, base64_data):\n        # Check if this is a base64 string\n        if isinstance(base64_data, basestring):\n            # Try to decode the file. Return validation error if it fails.\n            try:\n                decoded_file = base64.b64decode(base64_data)\n            except TypeError:\n                raise serializers.ValidationError(_(u\"Please upload a valid image.\"))\n\n            # Generate file name:\n            file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.\n            # Get the file name extension:\n            file_extension = self.get_file_extension(file_name, decoded_file)\n            self.check_file_extension(file_extension)\n            complete_file_name = file_name + \".\" + file_extension\n            data = ContentFile(decoded_file, name=complete_file_name)\n        else:\n            data = base64_data\n            file_extension = self.get_file_extension(data.name, data.read())\n            self.check_file_extension(file_extension)\n            data.seek(0)\n\n        return super(Base64ImageField, self).from_native(data)\n\n    def to_native(self, value):\n        \"\"\"\n        :param value: A Base64ImageField object\n        :return: a path to a thumbnail with a predetermined size, the default thumb\n        OR\n        a dict with a number of thumbnails, one of which is the default, the others being generated\n        from the query string parameters, and finally the path to the original image keyed to\n        \"original\".\n\n        The extended functionality, allowing the generation of one or more thumbnails from the\n        original image is triggered by including \"image_thumb_name\" in the query string. The value\n        for image_thumb_name is a comma separated list of identifiers for the generated thumbs.\n        The names must not be \"default\" or \"original\".\n\n        For each thumb thus specified a size must be supplied as a query param on the form\n            image_thumb_<name>_<dimension>\n        where <name> is the name of the thumb specified as one of the values for image_thumb_name\n        and <dimension> is one of \"width, \"height\" or \"max_size\". width and height must be an integer\n        specifying that dimension in pixels. The image will be scaled correctly in the other\n        dimension. max_size is width and height concatenated with an \"x\" and sets the maximum size\n        allowed for the respective dimensions, while still maintaining the correct aspect ratio of\n        the image.\n\n        Example:\n        the querystring\n            ?image_thumb_name=big,small&image_thumb_small_width=90&image_thumb_big_max_size=300x200\n        results in the following dict being returned:\n        {\n            'original': '/full/path/to/original/image.png',\n            'default': '/full/path/to/default/thumbnail/image.png',\n            'small': '/full/path/to/small/thumbnail/image.png',\n            'big': '/full/path/to/big/thumbnail/image.png',\n        }\n        This dict will be converted as appropriate to JSON or XML\n\n        NOTE: This special functionality works best when there is only one image field in a model.\n        If there are more, things will still work (I think), but for each image all thumbs returned\n        will have the same dimensions\n        \"\"\"\n        def get_thumb(request, name):\n            if name not in [u'original', u'default']:\n                try:\n                    width = request.GET.get('image_thumb_{}_width'.format(name))\n                    if width:\n                        return get_thumbnail(value, '{}'.format(width), quality=99)\n                    height = request.GET.get('image_thumb_{}_height'.format(name))\n                    if height:\n                        return get_thumbnail(value, 'x{}'.format(height), quality=99)\n                    # yes this is redundant...code is nearly identical with the width code above\n                    # but for clarity of function we keep them separate\n                    max_size = request.GET.get('image_thumb_{}_max_size'.format(name))\n                    if max_size:\n                        return get_thumbnail(value, '{}'.format(max_size), quality=99)\n                except (ThumbnailParseError, IOError):\n                    return None\n\n            # no size specification matching the name found; give up\n            return None\n\n        if value:\n            default_width = '191' # width of update images on akvo.org/seeithappen\n            try:\n                default_thumb = get_thumbnail(value, default_width, quality=99)\n                request = self.context['request']\n            except (ThumbnailParseError, IOError, KeyError):\n                return None\n\n            # look for name(s) of thumb(s)\n            image_thumb_name = request.GET.get('image_thumb_name')\n            if image_thumb_name:\n                names = image_thumb_name.split(',')\n                thumbs = {u'original': value.url, u'default': default_thumb.url}\n                for name in names:\n                    thumb = get_thumb(request, name)\n                    if thumb is not None:\n                        thumbs[name] = thumb.url\n                return thumbs\n            return default_thumb.url\n\n    def get_file_extension(self, filename, decoded_file):\n        extension = imghdr.what(filename, decoded_file)\n        extension = \"jpg\" if extension == \"jpeg\" else extension\n        return extension\n\n    def check_file_extension(self, file_extension):\n        if file_extension not in self.ALLOWED_IMAGE_TYPES:\n            formats = {'format': ', '.join(self.ALLOWED_IMAGE_TYPES)}\n            raise serializers.ValidationError(\n                _(u\"Unknown image type. Only the following types are accepted: %(format)s\") % formats\n            )\n", "path": "akvo/rest/fields.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Akvo RSR is covered by the GNU Affero General Public License.\n# See more details in the license.txt file located at the root folder of the Akvo RSR module.\n# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.\n\n\nimport base64\nimport imghdr\nimport six\nimport uuid\n\nfrom django.core.files.base import ContentFile\nfrom django.utils.encoding import smart_text\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom rest_framework import serializers\nfrom rest_framework.fields import ImageField\nfrom sorl.thumbnail import get_thumbnail\nfrom sorl.thumbnail.parsers import ThumbnailParseError\n\n\nclass NonNullCharField(serializers.CharField):\n    \"\"\" Fix fo CharField so that '' is returned if the field value is None\n        see https://github.com/tomchristie/django-rest-framework/pull/1665\n    \"\"\"\n    def from_native(self, value):\n        if isinstance(value, six.string_types):\n            return value\n        if value is None:\n            return u''\n        return smart_text(value)\n\n\nclass NonNullURLField(NonNullCharField, serializers.URLField):\n    pass\n\n\nclass Base64ImageField(ImageField):\n    \"\"\" A django-rest-framework field for handling image-uploads through raw post data.\n        It uses base64 for en-/decoding the contents of the file.\n        Now also supports thumbnails of different sizes. See to_native() for more info.\n    \"\"\"\n    ALLOWED_IMAGE_TYPES = (\n        'gif',\n        'jpeg',\n        'jpg',\n        'png',\n    )\n    def from_native(self, base64_data):\n        if base64_data is None:\n            data = base64_data\n        # Check if this is a base64 string\n        elif isinstance(base64_data, basestring):\n            # Try to decode the file. Return validation error if it fails.\n            try:\n                decoded_file = base64.b64decode(base64_data)\n            except TypeError:\n                raise serializers.ValidationError(_(u\"Please upload a valid image.\"))\n\n            # Generate file name:\n            file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.\n            # Get the file name extension:\n            file_extension = self.get_file_extension(file_name, decoded_file)\n            self.check_file_extension(file_extension)\n            complete_file_name = file_name + \".\" + file_extension\n            data = ContentFile(decoded_file, name=complete_file_name)\n        else:\n            data = base64_data\n            file_extension = self.get_file_extension(data.name, data.read())\n            self.check_file_extension(file_extension)\n            data.seek(0)\n\n        return super(Base64ImageField, self).from_native(data)\n\n    def to_native(self, value):\n        \"\"\"\n        :param value: A Base64ImageField object\n        :return: a path to a thumbnail with a predetermined size, the default thumb\n        OR\n        a dict with a number of thumbnails, one of which is the default, the others being generated\n        from the query string parameters, and finally the path to the original image keyed to\n        \"original\".\n\n        The extended functionality, allowing the generation of one or more thumbnails from the\n        original image is triggered by including \"image_thumb_name\" in the query string. The value\n        for image_thumb_name is a comma separated list of identifiers for the generated thumbs.\n        The names must not be \"default\" or \"original\".\n\n        For each thumb thus specified a size must be supplied as a query param on the form\n            image_thumb_<name>_<dimension>\n        where <name> is the name of the thumb specified as one of the values for image_thumb_name\n        and <dimension> is one of \"width, \"height\" or \"max_size\". width and height must be an integer\n        specifying that dimension in pixels. The image will be scaled correctly in the other\n        dimension. max_size is width and height concatenated with an \"x\" and sets the maximum size\n        allowed for the respective dimensions, while still maintaining the correct aspect ratio of\n        the image.\n\n        Example:\n        the querystring\n            ?image_thumb_name=big,small&image_thumb_small_width=90&image_thumb_big_max_size=300x200\n        results in the following dict being returned:\n        {\n            'original': '/full/path/to/original/image.png',\n            'default': '/full/path/to/default/thumbnail/image.png',\n            'small': '/full/path/to/small/thumbnail/image.png',\n            'big': '/full/path/to/big/thumbnail/image.png',\n        }\n        This dict will be converted as appropriate to JSON or XML\n\n        NOTE: This special functionality works best when there is only one image field in a model.\n        If there are more, things will still work (I think), but for each image all thumbs returned\n        will have the same dimensions\n        \"\"\"\n        def get_thumb(request, name):\n            if name not in [u'original', u'default']:\n                try:\n                    width = request.GET.get('image_thumb_{}_width'.format(name))\n                    if width:\n                        return get_thumbnail(value, '{}'.format(width), quality=99)\n                    height = request.GET.get('image_thumb_{}_height'.format(name))\n                    if height:\n                        return get_thumbnail(value, 'x{}'.format(height), quality=99)\n                    # yes this is redundant...code is nearly identical with the width code above\n                    # but for clarity of function we keep them separate\n                    max_size = request.GET.get('image_thumb_{}_max_size'.format(name))\n                    if max_size:\n                        return get_thumbnail(value, '{}'.format(max_size), quality=99)\n                except (ThumbnailParseError, IOError):\n                    return None\n\n            # no size specification matching the name found; give up\n            return None\n\n        if value:\n            default_width = '191' # width of update images on akvo.org/seeithappen\n            try:\n                default_thumb = get_thumbnail(value, default_width, quality=99)\n                request = self.context['request']\n            except (ThumbnailParseError, IOError, KeyError):\n                return None\n\n            # look for name(s) of thumb(s)\n            image_thumb_name = request.GET.get('image_thumb_name')\n            if image_thumb_name:\n                names = image_thumb_name.split(',')\n                thumbs = {u'original': value.url, u'default': default_thumb.url}\n                for name in names:\n                    thumb = get_thumb(request, name)\n                    if thumb is not None:\n                        thumbs[name] = thumb.url\n                return thumbs\n            return default_thumb.url\n\n    def get_file_extension(self, filename, decoded_file):\n        extension = imghdr.what(filename, decoded_file)\n        extension = \"jpg\" if extension == \"jpeg\" else extension\n        return extension\n\n    def check_file_extension(self, file_extension):\n        if file_extension not in self.ALLOWED_IMAGE_TYPES:\n            formats = {'format': ', '.join(self.ALLOWED_IMAGE_TYPES)}\n            raise serializers.ValidationError(\n                _(u\"Unknown image type. Only the following types are accepted: %(format)s\") % formats\n            )\n", "path": "akvo/rest/fields.py"}]}