为啥在 django 的响应错误中没有设置 .accepted_renderer?

Posted

技术标签:

【中文标题】为啥在 django 的响应错误中没有设置 .accepted_renderer?【英文标题】:Why getting .accepted_renderer not set on Response error in django?为什么在 django 的响应错误中没有设置 .accepted_renderer? 【发布时间】:2022-01-16 11:22:18 【问题描述】:

我想返回对我的 react Js 前端的响应,这是我的代码

def save_stripe_info(request):
    email = 'testing@gmail.com'
    payment_method_id = 'pm_1K5xfXBbWBJ638dR1WMitwx1'
    # creating customer
    customer = stripe.Customer.create(
      email=email, payment_method=payment_method_id)
     
    return Response(status=status.HTTP_200_OK, 
      data=
        'message': 'Success', 
        'data': 'customer_id': customer.id 
        
    )        

但出现错误

AssertionError: .accepted_renderer 未在响应上设置

我该如何解决这个问题。我看到了这个How to resolve AssertionError: .accepted_renderer not set on Response in django and ajax 但这仅适用于 django 并将 html 页面作为模板返回

我该如何解决这个错误

【问题讨论】:

即使你不使用模板,你仍然需要@api_view,因为这个装饰器会处理Response. accepted_renderer 【参考方案1】:

在你的views.py文件from rest_framework.decorators import api_view然后在函数定义之前写@api_view(['POST'])

@api_view(['POST'])
def save_stripe_info(request):
    email = 'testing@gmail.com'
    payment_method_id = 'pm_1K5xfXBbWBJ638dR1WMitwx1'
    # creating customer
    customer = stripe.Customer.create(
      email=email, payment_method=payment_method_id)
     
    return Response(status=status.HTTP_200_OK, 
      data=
        'message': 'Success', 
        'data': 'customer_id': customer.id 
        
    )     

希望这能解决您的问题!

【讨论】:

以上是关于为啥在 django 的响应错误中没有设置 .accepted_renderer?的主要内容,如果未能解决你的问题,请参考以下文章