【问题标题】:Django Rest Framework - object has no attribute postDjango Rest Framework - 对象没有属性 post
【发布时间】:2019-04-30 19:20:52
【问题描述】:

我的 urls.py 中有这个网址

 path('foo/bar/api', foo.APIBar.as_view(), name='foo-bar-api'),

在我的 view.py 中,我有这个类来处理 api:

class APIBar(APIView):
def post(request, self, format=None):        
    date= request.POST['date']
    person= get_object_or_404(Person, id=request.POST['person'])  
    return Response(status=status.HTTP_201_CREATED)

我正在尝试发送这个 ajax:

$.ajax({
            url: "{% url 'foo-bar-api' %}",
            method: "POST",
            data: {
                date: date.val(),
                person: person.val()
            }
        });

但是 Django 它给了我这个错误:

AttributeError: 'APIBar' object has no attribute 'POST'

我不知道为什么会这样。我在其他模型中使用了相同的结构并且像一个魅力一样工作,但是这个它给出了这个错误。

拜托,你能告诉我我做错了什么吗?我花了几个小时试图修复这个错误。

【问题讨论】:

    标签: python ajax django django-rest-framework


    【解决方案1】:

    您的post 方法的参数安排是错误的,正确的应该是:

    def post(self, request, format=None):
        date= request.POST['date']
        person= get_object_or_404(Person, id=request.POST['person'])  
        return Response(status=status.HTTP_201_CREATED)
    

    顺便说一句,self 这里表示对象引用。所以它应该是对象方法的第一个参数。

    【讨论】:

      猜你喜欢
      • 2015-10-15
      • 2017-03-04
      • 2021-05-02
      • 2018-09-13
      • 2020-12-24
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多