add extra parameter to request.DATA and fill serializer field using DJANGO REST FRAMEWORK

4,472 views
Skip to first unread message

Eddwin Paz

unread,
Apr 28, 2014, 5:33:52 AM4/28/14
to django-res...@googlegroups.com
I need to add an extra parameter to the request.DATA. In this case the variable opentok_session needs to fill the field opentok_sessionid on the startCallSerializer

Im sending (tutorID, studentID)

need to save

(tutorID, studentID, opentok_sessionid)

if i try doing 

post_values = request.POST.copy()
post_values['opentok_sessionid'] = opentok_session

it adds the value as expected but wont validate using serializers.is_valid() if empty POST is sent.

so i need to find a better way to save the value opentok_session and return opentok_sessionid

Thanks in advance for your help.



views.py

@api_view(['POST'])
def startCall(request):

if request.method == 'POST':

    API_KEY = '00000'
    API_SECRET = '000000000000000'
    OTSDK = OpenTokSDK.OpenTokSDK(API_KEY, API_SECRET)
    
    opentok_session = str(OTSDK.create_session().session_id)

    serializer = startCallSerializer(data=post_values)

    if serializer.is_valid():

        serializer.save()

        return Response(serializer.data, status=status.HTTP_201_CREATED)

    else:

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Views.py
class startCallSerializer(serializers.ModelSerializer):

class Meta:
    model = call
    fields = ('tutor', 'billed','opentok_sessionid')
    exclude = ('tutor','billed')

Malcolm Box

unread,
Jun 8, 2014, 6:39:30 PM6/8/14
to django-res...@googlegroups.com
You can use the context parameter to pass anything you like into a serializer, and then use that wherever you need.

E.g.

serializer = startCallSerializer(data=post_values, context={'open_tok': opentok_session)
Then in your serializer, you can inject this into the data dictionary for restore:
class startCallSerializer(...):
   def from_native(self, data, files):
        data['opentok_sessionid'] = self.context['open_tok']
        return super(startCallSerializer, self).from_native(data, files)

Hope that helps.,

Malcolm
Reply all
Reply to author
Forward
0 new messages