I know there are a few posts about this very same problem but the solution is to be found in some error made in the code that I can't figure out. So I'm posting here what I have written so far, hoping for your help. I have a class Node and I get the error stated in the title when I perform a POST. This is my code:
class NodeResource(ModelResource):
class Meta:
queryset = api.models.Node.objects.all()
resource_name = _Helpers.node_resource_name
always_return_data = True
# Allow retrieving large quantities of nodes at once.
limit = 250
max_limit = 0
filtering = {'name', 'is_ulg', 'latitude', 'longitude'}
allowed_methods = ['get', 'post']
authentication = Authentication()
authorization = Authorization()
def obj_create(self, bundle, **kwargs):
node = api.models.Node(name=bundle.data['name'],
is_ulg=bundle.data['is_ulg'],
latitude=bundle.data.get("latitude"),
longitude=bundle.data.get("longitude"))
node.save()
The model is the following:
class Node(models.Model):
"""
Represents a node in the graph.
"""
name = models.CharField(max_length=255)
is_ulg = models.BooleanField(default=False, verbose_name='Is this node a member of the ULg?')
latitude = models.FloatField()
longitude = models.FloatField()
def __str__(self):
return self.name
class Meta:
ordering = ['name']
unique_together = ("latitude", "longitude")
When I perform a post with the following json
{"name":"Node name","latitude": "2.4567", "longitude":"2.345", "is_ulg":false}
The node is correctly created, but I always get the error stated in the title. The full error is the following:
{"error_message":"'NoneType' object has no attribute 'obj'","traceback":"Traceback (most recent call last):\n\n File \"\/usr\/lib\/python2.7\/site-packages\/tastypie\/resources.py\", line 202, in wrapper\n response = callback(request, *args, **kwargs)\n\n File \"\/usr\/lib\/python2.7\/site-packages\/tastypie\/resources.py\", line 433, in dispatch_list\n return self.dispatch('list', request, **kwargs)\n\n File \"\/usr\/lib\/python2.7\/site-packages\/tastypie\/resources.py\", line 465, in dispatch\n response = method(request, **kwargs)\n\n File \"\/usr\/lib\/python2.7\/site-packages\/tastypie\/resources.py\", line 1347, in post_list\n updated_bundle = self.full_dehydrate(updated_bundle)\n\n File \"\/usr\/lib\/python2.7\/site-packages\/tastypie\/resources.py\", line 853, in full_dehydrate\n bundle.data[field_name] = field_object.dehydrate(bundle, for_list=for_list)\n\n File \"\/usr\/lib\/python2.7\/site-packages\/tastypie\/fields.py\", line 116, in dehydrate\n current_object = bundle.obj\n\nAttributeError: 'NoneType' object has no attribute 'obj'\n"}
Any idea what I'm doing wrong? Thanks!
Your object_create
function is implicitly returning None
, but Tastypie is expecting it to return a bundle. See how it is implemented in the docs example.
However, since it doesn't seem like you're using non-ORM data, you could just skip obj_create
and let Tastypie create the resource for you.