Django not redirecting to the web page
I am creating a messaging application in django with a built-in DLP system. I want to redirect to a web page when a sensitive word is detected in the message. But the webpage is not being redirected to. It is showing in the terminal but not on the front-end.
In consumers.py
async def chat_message(self, event):
message = event['message']
username = event['username']
if (re.findall("yes|Yes", message)):
response = await requests.get('http://127.0.0.1:8000/dlp/')
print('message')
else:
await self.send(text_data=json.dumps({
'message': message,
'username': username
}))
The output in the terminal
WebSocket CONNECT /ws/2/ [127.0.0.1:32840]
HTTP GET /dlp/ 200 [0.00, 127.0.0.1:32842]
message
Now your backends requests /dlp page, receives the response and prints string 'message' to console. It doesn't send any data to frontend.
The most simple solution, I think, will be to add status field to your json and handle it in javascript.
async def chat_message(self, event):
message = event['message']
username = event['username']
if re.findall("yes|Yes", message):
print('message')
await self.send(text_data=json.dumps({
'status': 1,
'redirect_to': '/dlp/',
}))
else:
await self.send(text_data=json.dumps({
'status': 0,
'message': message,
'username': username,
}))
const socket = new WebSocket(...) // url of WS here
socket.onmessage = ev => {
data = json.loads(ev.data);
if (data.status === 1){
window.location.href = new URL(data.redirect_to, window.location.origin);
} else if (!data.status) {
// handle normal message
} else {
alert('Error code forgotten!')
}
}