簡體   English   中英

Django'NoneType'對象沒有屬性'obj'

[英]Django 'NoneType' object has no attribute 'obj'

我知道有一些關於這個相同問題的文章,但是解決方案是在我不知道的代碼錯誤中找到的。 因此,我將在此發布我到目前為止所寫的內容,希望對您有所幫助。 我有一個Node類,執行POST時出現標題中指出的錯誤。 這是我的代碼:

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()

該模型如下:

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") 

當我使用以下json執行帖子時

{"name":"Node name","latitude": "2.4567", "longitude":"2.345", "is_ulg":false}

節點已正確創建,但是我總是收到標題中指出的錯誤。 完整的錯誤如下:

{"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"}

知道我在做什么錯嗎? 謝謝!

您的object_create函數隱式返回None ,但是Tastypie期望它返回一個包。 請參閱docs示例中的實現方法

但是,由於您似乎沒有使用非ORM數據,因此可以跳過obj_create ,讓Tastypie為您創建資源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM