Issue
I'm trying to send a form using the API endpoint beneath. The problem is that I get a 400 error when I use my react based application. If I'm using the api endpoint page it works. I checked the payload and the only difference seems to be that i'm not sending a csrf token in my react app. So far it was never neccesary when i used model serializers. I believe it is something inside the serializer but i cannot pin it down. Does anyone know what might be causing the 400 error?
sendEmail.js
const testmessage = "This is a test message"
const testemail = "[email protected]"
const clientnametest = "name"
function sendProposal(values) {
console.log("start sending proposal...");
setSendProp(true)
const data = new FormData()
data.append("Clientname", clientnametest || "");
data.append("Sender", testemail || "");
data.append("Message", testmessage || "");
axios.post(API.email.proposal, data, {
headers: {
"Authorization": `Bearer ${accessToken}`,
'Accept' : 'application/json',
},
withCredentials: true,
})
.then(res => {
})
.finally(() => {
setSendProp(false)
})
success()
}
views.py
class ProposalEmailView(APIView):
permission_classes = [IsAuthenticated]
serializer_class = ProposalEmailSerializer
def post(self, request, *args, **kwargs):
serializer_class = ProposalEmailSerializer(data=request.data)
if serializer_class.is_valid():
data = serializer_class.validated_data
ClientName = data.get('ClientName')
Sender = data.get('Sender')
Message = data.get('Message')
send_mail('Contact Form mail from ' + ClientName,
Message, Sender, ['[email protected]'],)
return Response({"success": "Sent"}, status=status.HTTP_200_OK)
return Response({"error": "Failed"}, status=status.HTTP_400_BAD_REQUEST)
serializers.py
class ProposalEmailSerializer(serializers.Serializer):
ClientName = serializers.CharField()
Sender = serializers.EmailField()
Message = serializers.CharField()
Solution
This fixed it for me. Using the generic views was my issue:
views.py
@api_view(['POST',])
def proposal(request):
if request.method == "POST":
serializer = ProposalEmailSerializer(data=request.data)
if serializer.is_valid():
ClientName = request.POST['ClientName']
Sender = request.POST['Sender']
Message = request.POST['Message']
# send mail
send_mail(
'Contact Form mail from ' + ClientName,
Message,
'[email protected]',
[Sender],
)
# serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Answered By - Matthias
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.