修复AttributeError:“ str”对象没有属性“ HTTP_201_CREATED”

时间:2018-12-11 13:00:34

标签: django python-3.x django-rest-framework

我已经在视图集上实现了以下方法,并且在发布AttributeError: 'str' object has no attribute 'HTTP_201_CREATED'时遇到问题。由于data已被序列化为json格式,为什么会收到此错误消息。

def create(self, request,*args, **kwargs):
        # Payload Items 
        paid_to = request.data['paid_to']
        paid_from = request.data['paid_from']
        amount = request.data['amount']
        description = request.data['description']
        date = request.data['date']
        status = request.data['status']

        # System Item
        auth_= get_auth(request)
        # Limit currency choices if setup
        default_currency = DEFAULT_CURRENCY
        # Get Transaction Type & show cr and dr accounts involved:
        transaction_type = TransactionType.objects.get(id=request.data['transaction_type'])
        get_credit_account = transaction_type.credit_account
        get_debit_account = transaction_type.debit_account 

        # Money To Internal Value 
        amount_to = Money(amount,DEFAULT_CURRENCY)

        # Auto generate transaction number 
        transaction_number = increment_transaction_number()

        # Create Transaction objects 

        transaction = Transaction.objects.create(
            transaction_type=transaction_type,
            organization=auth_,
            paid_to=paid_to,
            paid_from=paid_from,
            description=description,
            date=date,
            amount=amount_to,
            transaction_number=transaction_number)
        trans_id = transaction.id
        # print(trans_id)
        # Add directions to legs  ..note positive direction is DEBIT and negative direction is CREDIT
        positive_direction = 1
        negative_direction = -1


        # Add leg objects instances to track debits and credits TODO can add mutiple legs

        Leg.objects.create(transaction=Transaction.objects.get(id=transaction.id), account=get_credit_account, description=transaction.description, amount=+amount_to * positive_direction)
        Leg.objects.create(transaction=Transaction.objects.get(id=transaction.id), account=get_debit_account, description=transaction.description, amount=-amount_to * negative_direction)

        serializer = CreateTransactionSerializer(transaction)

        from rest_framework.renderers import JSONRenderer
        data = JSONRenderer().render(serializer.data)
        return Response(data, status=status.HTTP_201_CREATED, headers=headers)

2 个答案:

答案 0 :(得分:1)

此错误与您的序列化无关。它来自最后一行,您发送给Response的参数之一是status=status.HTTP_201_CREATED。但是status是您在方法开始时定义的内容:status = request.data['status']。因此,它是一个字符串,并且没有所谓的属性。

很显然,您打算在模块顶部引用从status导入的rest_framework模块。但是您的字符串变量将其隐藏。您需要更改变量的名称。

答案 1 :(得分:0)

您正在使用此行覆盖rest_framework.status

status = request.data['status']

您需要将此变量重命名为其他名称才能使用

status.HTTP_201_CREATED来自rest_framework