Answer the question
In order to leave comments, you need to log in
How to handle an arbitrary request to Django Rest Framework?
The task is to receive data from Angular and process it in some way (let's say send a message to telegram. The problem is that either HttpClient does not send a request, or Django does not return it.
Angular's request sending code:
sendMessage(){
if(this.reCaptchaRes!=null){
alert("Сообщение отправлено в телеграм!")
this.http.get('http://127.0.0.1:8000/api/v1/sendMessage/')
.subscribe((responce)=>{
console.log('Responce:')
console.log(responce)
})
}
else{
alert("Вы должны пройти проверку reCaptcha")
}
}
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.views import APIView
class MessageView(APIView):
def get(self, request):
data=request.POST
responce=dict(error=0, message="Message send", success=True)
return Response(responce)
Answer the question
In order to leave comments, you need to log in
Maybe someone needs it. The problem was in the csrf token. Solved the problem but as for me it's a crutch.
1 included csrf_exempt in the url file Api/ urlls.py :
from django.urls import path, include
from django.views.decorators.csrf import csrf_exempt
from Sites.views import SiteListView
from .views import messagePost
app_name= 'Sites'
urlpatterns = [
path('Site/all/', SiteListView.as_view()),
path('sendMessage/', csrf_exempt(messagePost)),
]
from django.shortcuts import render
import json
import requests
from django.http import JsonResponse
from rest_framework.response import Response
def messagePost(request):
data = json.loads(request.body.decode())
responce=dict(error=0, message="Message send", success=True)
token = "TELEGRAM_TOKEN"
url = "https://api.telegram.org/bot"
channel_id = "CHAT_ID"
url += token
method = url + "/sendMessage"
text="Имя: \n "+str(data.get('name'))+"\n Email: \n "+str(data.get('email'))+"\n Телефон:\n "+str(data.get('phone'))+"\n Сообщение:\n "+str(data.get('message'))
r = requests.post(method, data={
"chat_id": channel_id,
"text": text
})
if r.status_code != 200:
responce['error'] = 5
responce['message']="Возникла ошибка"
return JsonResponse(responce)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question