Issue
I am new to Django Rest Framework and appreciate the help from this community. I am making an AJAX call to some Django Rest Framework APIs in the backend and I would like to pass the name of the javascript function to be called in the UI upon successful completion of the request.
AJAX Function
var saveEditedData = function (event) {
let parentElement = event.parentElement;
let enctype = (event.enctype) ? event.enctype : "application/x-www-form-urlencoded";
let method = (event.method) ? event.method : "POST";
$.ajax({
cache: false,
contentType: false,
data: event.data,
enctype: enctype,
processData: false,
type: method,
url: event.url,
success: function (response){
console.log(response);
if (response['onSuccessFn']){
successFns[response['onSuccessFn']](response);
}
},
error: function (response) {
let errors = response["responseJSON"]["errors"];
displayErrors(parentElement, errors);
}
});
}
DJANGO REST Serializer Class
class DocumentCategorySerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
on_success_fn = serializers.SerializerMethodField()
class Meta:
model = DocumentCategory
fields = ['id', 'name', 'description', 'on_success_fn']
def get_on_success_fn(self, obj):
return self.data['on_success_fn']
**Sample Inbound Data to Serializer**
[name : TestCategory]
[description: Testing this]
[on_success_fn: addCategorySuccessFn]
The idea is that I use one AJAX function across multiple UI interactions and the method to be called on success is dynamically executed on return. I have a model serializer but all the fields are derived from the database. I added a SerializerMethodField but it doesn't pass through the input value. I need one field to be a 'pass-through' - it just sends the same value it received in input to output.
Question: How do I pass a field inbound and outbound to Django Rest Framework?
Solution
self.data
is actually a method, you will end up in a infinite recursion if you call it from a field. Use self.initial_data
instead.
class DocumentCategorySerializer(serializers.ModelSerializer):
on_success_fn = serializers.SerializerMethodField()
class Meta:
model = DocumentCategory
fields = ['id', 'name', 'description', 'on_success_fn']
read_only_field = ('id',)
def get_on_success_fn(self, obj):
return self.initial_data['on_success_fn']
Answered By - Julkar9
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.