我正在尝试在DRF中创建自定义渲染方法,以下是我的代码:
序列化程序
class SupplierSerializer(serializers.ModelSerializer):
class Meta:
model = models.Supplier
fields = [
# "plan",
"type",
"created",
"id",
"name",
"bio",
"established",
"logo",
"last_updated",
"is_active",
"date_to_pay",
"mobile",
"password",
]
渲染器
class ApiRenderer(BaseRenderer):
media_type = 'text/plain'
format = 'txt'
def render(self, data, accepted_media_type=None, renderer_context=None):
response_dict = {
'status': 'failure',
'data': {},
'message': '',
}
if data.get('data'):
response_dict['data'] = data.get('data')
if data.get('status'):
response_dict['status'] = data.get('status')
if data.get('message'):
response_dict['message'] = data.get('message')
data = response_dict
return json.dumps(data)
设置
RENDERER_CLASSES = (
'market_control_panel.renderers.ApiRenderer',
)
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication', # <-- And here
'rest_framework.authentication.TokenAuthentication', # <-- And here
],
# testing ftp upload after comment
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_RENDERER_CLASSES': RENDERER_CLASSES,
}
但当我尝试打开任何API链接时,会出现以下错误:
'ReturnList' object has no attribute 'get'
render(...)
方法的data
参数可以是任何东西,例如,list
、dict
、string
{data
由视图(函数或类)返回,您应该期望它是任何东西在您的情况下,视图可能返回类似列表的响应(假设您访问了列表视图),因此返回的对象不支持
<>我不确定你在做什么,但是,你应该在更新渲染逻辑时考虑这一点。.get()
方法,因此出现错误相关问题 更多 >
编程相关推荐