django rest serialize a string when model object is not defined












0














having trouble serializer a string during a try/except statement.



here i have a endpoint that calls another function refund the response i get back from that function i'm trying to serialize.




class RefundOrder(APIView):
def post(self, request, **kwargs):
print('test')
body_unicode = request.body.decode('utf-8')
body_data = json.loads(body_unicode)
amount = body_data['amount']
tenant = get_object_or_404(Tenant, pk=kwargs['tenant_id'])

refund = SquareGateway(tenant).refund(amount)
serializer = RefundSerializer(refund)
return Response(serializer.data)





this is the function that gets called in the post endpoint. i added it in a try statement to handle the errors from square api. if the api call fails, i want to return an error if their is one, else serialize that data.




    def refund(self, order, amount, reason):

try:
response = self.client.transaction().create_refund(stuff)

refund = Refund(
order=order,
amount=response.refund.amount_money.amount,
)
refund.save()
return refund
except ApiException as e:
return json.loads(e.body)['errors'][0]['detail']





this is the the Refundserialize




class RefundSerializer(serializers.ModelSerializer):
class Meta:
model = Refund
fields = ('id', 'amount')





serializing the string doesn't throw an error it just doesn't return the error message that im returning.Currently it returns a empty serialized object.










share|improve this question
























  • What's your question? Does your code produce an error message? If so post the traceback.
    – Red Cricket
    Nov 21 at 0:35










  • sorry about that just updated my question.
    – David Ramirez
    Nov 21 at 0:41










  • So your problem must be coming from this statement json.loads(e.body)['errors'][0]['detail']
    – Red Cricket
    Nov 21 at 0:42










  • yes so json.loads(e.body)['errors'][0]['detail'] returns a string One or more refunds might already have been applied to this payment and when i pass that string to ` RefundSerializer(refund)` returns a an empty object like this {"amount": null} i want to return that string instead of the object. if the api call fails.
    – David Ramirez
    Nov 21 at 0:49












  • So you want to return an object that looks like {"amount": "One or more refunds might already have been applied to this payment"}, right?
    – Red Cricket
    Nov 21 at 0:52
















0














having trouble serializer a string during a try/except statement.



here i have a endpoint that calls another function refund the response i get back from that function i'm trying to serialize.




class RefundOrder(APIView):
def post(self, request, **kwargs):
print('test')
body_unicode = request.body.decode('utf-8')
body_data = json.loads(body_unicode)
amount = body_data['amount']
tenant = get_object_or_404(Tenant, pk=kwargs['tenant_id'])

refund = SquareGateway(tenant).refund(amount)
serializer = RefundSerializer(refund)
return Response(serializer.data)





this is the function that gets called in the post endpoint. i added it in a try statement to handle the errors from square api. if the api call fails, i want to return an error if their is one, else serialize that data.




    def refund(self, order, amount, reason):

try:
response = self.client.transaction().create_refund(stuff)

refund = Refund(
order=order,
amount=response.refund.amount_money.amount,
)
refund.save()
return refund
except ApiException as e:
return json.loads(e.body)['errors'][0]['detail']





this is the the Refundserialize




class RefundSerializer(serializers.ModelSerializer):
class Meta:
model = Refund
fields = ('id', 'amount')





serializing the string doesn't throw an error it just doesn't return the error message that im returning.Currently it returns a empty serialized object.










share|improve this question
























  • What's your question? Does your code produce an error message? If so post the traceback.
    – Red Cricket
    Nov 21 at 0:35










  • sorry about that just updated my question.
    – David Ramirez
    Nov 21 at 0:41










  • So your problem must be coming from this statement json.loads(e.body)['errors'][0]['detail']
    – Red Cricket
    Nov 21 at 0:42










  • yes so json.loads(e.body)['errors'][0]['detail'] returns a string One or more refunds might already have been applied to this payment and when i pass that string to ` RefundSerializer(refund)` returns a an empty object like this {"amount": null} i want to return that string instead of the object. if the api call fails.
    – David Ramirez
    Nov 21 at 0:49












  • So you want to return an object that looks like {"amount": "One or more refunds might already have been applied to this payment"}, right?
    – Red Cricket
    Nov 21 at 0:52














0












0








0







having trouble serializer a string during a try/except statement.



here i have a endpoint that calls another function refund the response i get back from that function i'm trying to serialize.




class RefundOrder(APIView):
def post(self, request, **kwargs):
print('test')
body_unicode = request.body.decode('utf-8')
body_data = json.loads(body_unicode)
amount = body_data['amount']
tenant = get_object_or_404(Tenant, pk=kwargs['tenant_id'])

refund = SquareGateway(tenant).refund(amount)
serializer = RefundSerializer(refund)
return Response(serializer.data)





this is the function that gets called in the post endpoint. i added it in a try statement to handle the errors from square api. if the api call fails, i want to return an error if their is one, else serialize that data.




    def refund(self, order, amount, reason):

try:
response = self.client.transaction().create_refund(stuff)

refund = Refund(
order=order,
amount=response.refund.amount_money.amount,
)
refund.save()
return refund
except ApiException as e:
return json.loads(e.body)['errors'][0]['detail']





this is the the Refundserialize




class RefundSerializer(serializers.ModelSerializer):
class Meta:
model = Refund
fields = ('id', 'amount')





serializing the string doesn't throw an error it just doesn't return the error message that im returning.Currently it returns a empty serialized object.










share|improve this question















having trouble serializer a string during a try/except statement.



here i have a endpoint that calls another function refund the response i get back from that function i'm trying to serialize.




class RefundOrder(APIView):
def post(self, request, **kwargs):
print('test')
body_unicode = request.body.decode('utf-8')
body_data = json.loads(body_unicode)
amount = body_data['amount']
tenant = get_object_or_404(Tenant, pk=kwargs['tenant_id'])

refund = SquareGateway(tenant).refund(amount)
serializer = RefundSerializer(refund)
return Response(serializer.data)





this is the function that gets called in the post endpoint. i added it in a try statement to handle the errors from square api. if the api call fails, i want to return an error if their is one, else serialize that data.




    def refund(self, order, amount, reason):

try:
response = self.client.transaction().create_refund(stuff)

refund = Refund(
order=order,
amount=response.refund.amount_money.amount,
)
refund.save()
return refund
except ApiException as e:
return json.loads(e.body)['errors'][0]['detail']





this is the the Refundserialize




class RefundSerializer(serializers.ModelSerializer):
class Meta:
model = Refund
fields = ('id', 'amount')





serializing the string doesn't throw an error it just doesn't return the error message that im returning.Currently it returns a empty serialized object.






class RefundOrder(APIView):
def post(self, request, **kwargs):
print('test')
body_unicode = request.body.decode('utf-8')
body_data = json.loads(body_unicode)
amount = body_data['amount']
tenant = get_object_or_404(Tenant, pk=kwargs['tenant_id'])

refund = SquareGateway(tenant).refund(amount)
serializer = RefundSerializer(refund)
return Response(serializer.data)





class RefundOrder(APIView):
def post(self, request, **kwargs):
print('test')
body_unicode = request.body.decode('utf-8')
body_data = json.loads(body_unicode)
amount = body_data['amount']
tenant = get_object_or_404(Tenant, pk=kwargs['tenant_id'])

refund = SquareGateway(tenant).refund(amount)
serializer = RefundSerializer(refund)
return Response(serializer.data)





    def refund(self, order, amount, reason):

try:
response = self.client.transaction().create_refund(stuff)

refund = Refund(
order=order,
amount=response.refund.amount_money.amount,
)
refund.save()
return refund
except ApiException as e:
return json.loads(e.body)['errors'][0]['detail']





    def refund(self, order, amount, reason):

try:
response = self.client.transaction().create_refund(stuff)

refund = Refund(
order=order,
amount=response.refund.amount_money.amount,
)
refund.save()
return refund
except ApiException as e:
return json.loads(e.body)['errors'][0]['detail']





class RefundSerializer(serializers.ModelSerializer):
class Meta:
model = Refund
fields = ('id', 'amount')





class RefundSerializer(serializers.ModelSerializer):
class Meta:
model = Refund
fields = ('id', 'amount')






python django django-models django-rest-framework






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 at 0:40

























asked Nov 21 at 0:28









David Ramirez

72111




72111












  • What's your question? Does your code produce an error message? If so post the traceback.
    – Red Cricket
    Nov 21 at 0:35










  • sorry about that just updated my question.
    – David Ramirez
    Nov 21 at 0:41










  • So your problem must be coming from this statement json.loads(e.body)['errors'][0]['detail']
    – Red Cricket
    Nov 21 at 0:42










  • yes so json.loads(e.body)['errors'][0]['detail'] returns a string One or more refunds might already have been applied to this payment and when i pass that string to ` RefundSerializer(refund)` returns a an empty object like this {"amount": null} i want to return that string instead of the object. if the api call fails.
    – David Ramirez
    Nov 21 at 0:49












  • So you want to return an object that looks like {"amount": "One or more refunds might already have been applied to this payment"}, right?
    – Red Cricket
    Nov 21 at 0:52


















  • What's your question? Does your code produce an error message? If so post the traceback.
    – Red Cricket
    Nov 21 at 0:35










  • sorry about that just updated my question.
    – David Ramirez
    Nov 21 at 0:41










  • So your problem must be coming from this statement json.loads(e.body)['errors'][0]['detail']
    – Red Cricket
    Nov 21 at 0:42










  • yes so json.loads(e.body)['errors'][0]['detail'] returns a string One or more refunds might already have been applied to this payment and when i pass that string to ` RefundSerializer(refund)` returns a an empty object like this {"amount": null} i want to return that string instead of the object. if the api call fails.
    – David Ramirez
    Nov 21 at 0:49












  • So you want to return an object that looks like {"amount": "One or more refunds might already have been applied to this payment"}, right?
    – Red Cricket
    Nov 21 at 0:52
















What's your question? Does your code produce an error message? If so post the traceback.
– Red Cricket
Nov 21 at 0:35




What's your question? Does your code produce an error message? If so post the traceback.
– Red Cricket
Nov 21 at 0:35












sorry about that just updated my question.
– David Ramirez
Nov 21 at 0:41




sorry about that just updated my question.
– David Ramirez
Nov 21 at 0:41












So your problem must be coming from this statement json.loads(e.body)['errors'][0]['detail']
– Red Cricket
Nov 21 at 0:42




So your problem must be coming from this statement json.loads(e.body)['errors'][0]['detail']
– Red Cricket
Nov 21 at 0:42












yes so json.loads(e.body)['errors'][0]['detail'] returns a string One or more refunds might already have been applied to this payment and when i pass that string to ` RefundSerializer(refund)` returns a an empty object like this {"amount": null} i want to return that string instead of the object. if the api call fails.
– David Ramirez
Nov 21 at 0:49






yes so json.loads(e.body)['errors'][0]['detail'] returns a string One or more refunds might already have been applied to this payment and when i pass that string to ` RefundSerializer(refund)` returns a an empty object like this {"amount": null} i want to return that string instead of the object. if the api call fails.
– David Ramirez
Nov 21 at 0:49














So you want to return an object that looks like {"amount": "One or more refunds might already have been applied to this payment"}, right?
– Red Cricket
Nov 21 at 0:52




So you want to return an object that looks like {"amount": "One or more refunds might already have been applied to this payment"}, right?
– Red Cricket
Nov 21 at 0:52












1 Answer
1






active

oldest

votes


















2














As far as I understood, You need a custom API exception which returns a custom message.

So, Initially create a custom exception class as below,



from rest_framework.exceptions import APIException
from rest_framework import status


class GenericAPIException(APIException):
"""
raises API exceptions with custom messages and custom status codes
"""
status_code = status.HTTP_400_BAD_REQUEST
default_code = 'error'

def __init__(self, detail, status_code=None):
self.detail = detail
if status_code is not None:
self.status_code = status_code





Then raise the exception in refund() function.



def refund(self, order, amount, reason):

try:
# your code
except ApiException as e:
raise GenericAPIException({"message":"my custom msg"})





share|improve this answer





















  • glad to hear that!
    – JPG
    Nov 21 at 6:06











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53403643%2fdjango-rest-serialize-a-string-when-model-object-is-not-defined%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














As far as I understood, You need a custom API exception which returns a custom message.

So, Initially create a custom exception class as below,



from rest_framework.exceptions import APIException
from rest_framework import status


class GenericAPIException(APIException):
"""
raises API exceptions with custom messages and custom status codes
"""
status_code = status.HTTP_400_BAD_REQUEST
default_code = 'error'

def __init__(self, detail, status_code=None):
self.detail = detail
if status_code is not None:
self.status_code = status_code





Then raise the exception in refund() function.



def refund(self, order, amount, reason):

try:
# your code
except ApiException as e:
raise GenericAPIException({"message":"my custom msg"})





share|improve this answer





















  • glad to hear that!
    – JPG
    Nov 21 at 6:06
















2














As far as I understood, You need a custom API exception which returns a custom message.

So, Initially create a custom exception class as below,



from rest_framework.exceptions import APIException
from rest_framework import status


class GenericAPIException(APIException):
"""
raises API exceptions with custom messages and custom status codes
"""
status_code = status.HTTP_400_BAD_REQUEST
default_code = 'error'

def __init__(self, detail, status_code=None):
self.detail = detail
if status_code is not None:
self.status_code = status_code





Then raise the exception in refund() function.



def refund(self, order, amount, reason):

try:
# your code
except ApiException as e:
raise GenericAPIException({"message":"my custom msg"})





share|improve this answer





















  • glad to hear that!
    – JPG
    Nov 21 at 6:06














2












2








2






As far as I understood, You need a custom API exception which returns a custom message.

So, Initially create a custom exception class as below,



from rest_framework.exceptions import APIException
from rest_framework import status


class GenericAPIException(APIException):
"""
raises API exceptions with custom messages and custom status codes
"""
status_code = status.HTTP_400_BAD_REQUEST
default_code = 'error'

def __init__(self, detail, status_code=None):
self.detail = detail
if status_code is not None:
self.status_code = status_code





Then raise the exception in refund() function.



def refund(self, order, amount, reason):

try:
# your code
except ApiException as e:
raise GenericAPIException({"message":"my custom msg"})





share|improve this answer












As far as I understood, You need a custom API exception which returns a custom message.

So, Initially create a custom exception class as below,



from rest_framework.exceptions import APIException
from rest_framework import status


class GenericAPIException(APIException):
"""
raises API exceptions with custom messages and custom status codes
"""
status_code = status.HTTP_400_BAD_REQUEST
default_code = 'error'

def __init__(self, detail, status_code=None):
self.detail = detail
if status_code is not None:
self.status_code = status_code





Then raise the exception in refund() function.



def refund(self, order, amount, reason):

try:
# your code
except ApiException as e:
raise GenericAPIException({"message":"my custom msg"})






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 21 at 1:26









JPG

13k2830




13k2830












  • glad to hear that!
    – JPG
    Nov 21 at 6:06


















  • glad to hear that!
    – JPG
    Nov 21 at 6:06
















glad to hear that!
– JPG
Nov 21 at 6:06




glad to hear that!
– JPG
Nov 21 at 6:06


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53403643%2fdjango-rest-serialize-a-string-when-model-object-is-not-defined%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Feedback on college project

Futebolista

Albești (Vaslui)