0

I am using Django rest framework, I have to add my custom data in the Response() object.

rsp = Response()
rsp['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(file)
rsp['X-Accel-Redirect'] = '/export/%s' % file

I want to add custome dict in the data part of this Response()

Hence I tried this,

data = {'length': 10}
rsp = Response(data)

and

data = {'length': 10}
rsp = Response()
rsp['data'] = data

But I was getting error as 'error:{'data'}'

Help me to understand why this behaviour occurred and How to add custom data in Response()

0

2 Answers 2

1

When you set rsp['data'], it is trying to set a header. This gives an error since data is a dictionary, not a string.

Instead, you should pass the response data as the first argument when you initialise the response:

from rest_framework.response import Response

data = {'length': 10}
rsp = Response(data)
...
Sign up to request clarification or add additional context in comments.

11 Comments

Thanks for quick response @Alasdair, I tried this approach also, but when I am doing hasattr(response, 'data') that its returning False and also my data is not retirevable
If I do rsp = Response(data), then hasattr(rsp, 'data') returns True and rsp.data gives the dict.
Can you tell me, what is possible mistake I am making that return this behaviour to me @Alasdair
It's difficult to help anymore unless you can give an example that reproduces the problem.
yeah that's fine, Is there are any scenario or implementation that forces this kind of behaviour or else you have faced this before?
|
0
data = {'length': 10}
return Response({'data': data})

so;

response = {}
response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(file)
response['X-Accel-Redirect'] = '/export/%s' % file
return Response(response)

3 Comments

Could you provide more details on the answer?
yeah, even I also not able to understand
@origamic can you explore more about your solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.