AttributeError:“NoneType”对象没有“保存”属性

Posted

技术标签:

【中文标题】AttributeError:“NoneType”对象没有“保存”属性【英文标题】:AttributeError: 'NoneType' object has no attribute 'save' 【发布时间】:2019-10-18 02:09:33 【问题描述】:

我正在尝试使用 react-facebook-login 登录 facebook,而不是存储数据,但它给了我一个关于“保存”的错误,我不明白为什么,我在其他应用程序中使用了完全相同的结构,它工作得很好,你能告诉我我做错了什么吗?

这是 models.py 代码:


class Social(EmbeddedDocument):
    name = StringField() 
    accountId = ReferenceField(Account)
    userId = StringField()
    project = ReferenceField(Project)
    email = EmailField()
    meta = 'allow_inheritance': True
    add_date = DateTimeField(default=datetime.datetime.now)

    def save(self, *args, **kwargs):
        if not self.add_date:
            self.add_date = datetime.datetime.now()
        self.add_date = datetime.datetime.now()
        return super(Social, self).save(*args, **kwargs)

class Facebook(Social):
    pageId = StringField(unique=True)

views.py

class FacebookCreateView(APIView):
    permission_classes = (AllowAny,)
    def post(self, request):
        serializer = FacebookSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializers.js

class FacebookSerializer(DocumentSerializer):
    class Meta:
        model = Facebook
        fields = ('name', 'accountId','userId','pageId','project','email')

    def create(self, validated_data):
        facebook_account = Facebook(
                        accountId=validated_data['accountId'],
                        name=validated_data['name'],
                        userId=validated_data['userId'],
                        pageId=validated_data['pageId'],
                        project=validated_data['project'],
                        email=validated_data['email'])
        facebook_account.save()
        return facebook_account

我正在调用的是来自前端的

  responseFacebook = (response) =>   
  console.log(response);
  let data = new FormData(); // creates a new FormData object
    data.append('name', response.name);
    data.append('email', response.email);
    data.append('userId', response.userID);
    data.append('accountId', '5ced550e927bd2cfc01264bc');
    data.append('project', '5ce5acf4ec67314c53cae53e');
    data.append('pageId', 'tobeadded');
    axios.post('http://127.0.0.1:8000/social/fb/', data)
    .then(res =>  if(res.status === 200)
      console.log(res))
    .catch(err=>console.log(err))
    //window.FB.logout();
  

它给了我这个错误:

Internal Server Error: /social/fb/
Traceback (most recent call last):
  File "C:\Users\Kouter\Desktop\pfeCode\backend\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Kouter\Desktop\pfeCode\backend\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Kouter\Desktop\pfeCode\backend\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Kouter\Desktop\pfeCode\backend\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\Kouter\Desktop\pfeCode\backend\env\lib\site-packages\django\views\generic\base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\Kouter\Desktop\pfeCode\backend\env\lib\site-packages\rest_framework\views.py", line 495, in dispatch
    response = self.handle_exception(exc)
  File "C:\Users\Kouter\Desktop\pfeCode\backend\env\lib\site-packages\rest_framework\views.py", line 455, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Users\Kouter\Desktop\pfeCode\backend\env\lib\site-packages\rest_framework\views.py", line 466, in raise_uncaught_exception
    raise exc
  File "C:\Users\Kouter\Desktop\pfeCode\backend\env\lib\site-packages\rest_framework\views.py", line 492, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Users\Kouter\Desktop\pfeCode\backend\social_accounts\views.py", line 17, in post
    serializer.save()
  File "C:\Users\Kouter\Desktop\pfeCode\backend\env\lib\site-packages\rest_framework\serializers.py", line 214, in save
    self.instance = self.create(validated_data)
  File "C:\Users\Kouter\Desktop\pfeCode\backend\social_accounts\serializers.py", line 18, in create
    facebook_account.save()
  File "C:\Users\Kouter\Desktop\pfeCode\backend\social_accounts\models.py", line 20, in save
    return super(Social, self).save(*args, **kwargs)
  File "C:\Users\Kouter\Desktop\pfeCode\backend\env\lib\site-packages\mongoengine\document.py", line 97, in save
    self._instance.save(*args, **kwargs)
AttributeError: 'NoneType' object has no attribute 'save'

【问题讨论】:

【参考方案1】:

一个 Document 代表一个 MongoDB 文档(即集合中的一条记录),一个 Document 类绑定到一个特定的集合。 EmbeddedDocument 表示嵌套在 Document 中的结构。

因此根据设计,除非您将 EmbeddedDocument 嵌入到 Document 中,否则它不会附加到任何集合中。

这意味着您无法查询或保存 EmbeddedDocument 类,您需要查询/保存父 Document。

在您的情况下,您的 EmbeddedDocument 实例未附加到父 Document 类。

让你的 Social 类继承自 Document 而不是 EmbeddedDocument,它应该是可保存的。

【讨论】:

我有同样的错误但不同的问题。声明字段时需要使用EmbeddedDocumentField 而不是EmbeddedDocument。最后一个是其他模型的超类,需要嵌入。

以上是关于AttributeError:“NoneType”对象没有“保存”属性的主要内容,如果未能解决你的问题,请参考以下文章

AttributeError:'NoneType'对象没有属性'upper'[关闭]

%Matplotlib - AttributeError: 'NoneType' 对象没有属性 'lower'

BeautifulSoup:AttributeError:“NoneType”对象没有属性“文本”

Elastic Beanstalk 部署错误:AttributeError :: 'NoneType' 对象没有属性 'split'

AttributeError:“NoneType”对象没有“当前”属性

每次我使用 pip 时都会出现“AttributeError:'NoneType'”