Reputation: 270
I am using django restframework to send a json like this :
[
{
"email" : "[email protected]",
"email" : "[email protected]",
"meeting_date":"2021-06-29",
"time_zone" : "Asia/Tehran"
}
]
and in views.py i need to get two fields like this:
serializer = EmailsListSerializer(data=request.data, many=True)
meeting_date = serializer.data['meeting_date']
meeting_timezone = serializer.data['time_zone']
but i got this error and don't know how to solve it :
TypeError at /user/prefertimes/
list indices must be integers or slices, not str
/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py, line 47, in inner
response = get_response(request)
Upvotes: 1
Views: 2185
Reputation: 46
serializer = EmailsListSerializer(data=request.data, many=True)
Here you're providing many=True
, which means that serializer.data
is a list of dictionaries rather than a single dictionary. So, you need to access the the dictionary data like this:
meeting_date = serializer.data[0]['meeting_date']
meeting_timezone = serializer.data[0]['time_zone']
Alternatively, if you're always sending just one dictionary in your list in the json, you can omit many=True
serializer = EmailsListSerializer(data=request.data)
and send a dictionary instead of a list of dictionaries.
{
"email" : "[email protected]",
"email" : "[email protected]",
"meeting_date":"2021-06-29",
"time_zone" : "Asia/Tehran"
}
Upvotes: 3