Cannot Resolve a 500 (Internal Server Error) Code - javascript

I have run into a 500 error that I cannot resolve while practicing with making a To Do app with various lists & to do items that all have full CRUD options.
To Do List code:
class TodoList (db.Model):
__tablename__ = 'todolists'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(), nullable=False)
todos = db.relationship('Todo', backref='list', lazy=True)
const todo_list_input = document.getElementById('todo_list_id');
document.getElementById('create_list_box_button').onsubmit = function(e) {
e.preventDefault();
const list_title = todo_list_input.value;
todo_list_input.value = '';
fetch('/todolists/create', {
method: 'POST',
body: JSON.stringify({
'todo_list_id': list_title,
}),
headers: {
'Contet-Type': 'application/json'
}
})
.then(response => response.json())
.then(jsonResponse => {
const li = document.createElement('li');
const checkbox = document.createElement('input');
checkbox.className = 'check-completed';
checkbox.type = 'checkbox';
checkbox.setAttribute('data-id', jsonResponse.id);
li.appendChild(checkbox);
const text = document.createTextNode(' ' + jsonResponse.description);
li.appendChild(text);
const deleteButton = document.createElement('button');
deleteButton.className = 'delete-button';
deleteButton.setAttribute('data-id', jsonResponse.id);
deleteButton.innerHTML = '✗';
li.appendChild(deleteButton);
document.getElementById('todo_lists_buttons').appendChild(li);
document.getElementById('error').className = 'hidden';
})
.catch(function() {
console.error('Error occurred');
document.getElementById('error').className = '';
})
}
#app.route('/todolists/create', methods=['POST'])
def create_todoList():
error = False
body = {}
try:
list_name = request.json()['list_name']
todoList = List(list_name=list_name)
db.session.add(todoList)
db.session.commit()
body['list_name'] = todoList.list_name
except:
error = True
db.session.rollback()
print(sys.exc_info())
finally:
db.session.close()
if not error:
return jsonify(body)
else:
abort(500)
I've tried changing variable names around throughout, no joy there, as well as a few other things to try to pinpoint the issue and am just out of ideas (still new at this) on what might be going on.
This only occurs when attempting to 'Create' a new To Do List. I can swap between lists and create/delete To Do Items no problem, it's just the Create List that isn't working.
To Do item code:
class Todo(db.Model):
__tablename__ = 'todos'
id = db.Column(db.Integer, primary_key=True)
description = db.Column(db.String(), nullable=False)
completed = db.Column(db.Boolean, default=False)
list_id = db.Column(db.Integer, db.ForeignKey('todolists.id'), nullable=False)
const todo_item_input = document.getElementById('description');
document.getElementById('create_todo_box_button').onsubmit = function(e) {
e.preventDefault();
const desc = todo_item_input.value;
todo_item_input.value = '';
fetch('/todos/create', {
method: 'POST',
body: JSON.stringify({
'description': desc,
'list_id': {{ active_list.id }}
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(jsonResponse => {
const li = document.createElement('li');
const checkbox = document.createElement('input');
checkbox.className = 'check-completed';
checkbox.type = 'checkbox';
checkbox.setAttribute('data-id', jsonResponse.id);
li.appendChild(checkbox);
const text = document.createTextNode(' ' + jsonResponse.description);
li.appendChild(text);
const deleteButton = document.createElement('button');
deleteButton.className = 'delete-button';
deleteButton.setAttribute('data-id', jsonResponse.id);
deleteButton.innerHTML = '✗';
li.appendChild(deleteButton);
document.getElementById('todos').appendChild(li);
document.getElementById('error').className = 'hidden';
})
.catch(function() {
console.error('Error occured');
document.getElementById('error').className = '';
})
}
#app.route('/todos/create', methods=['POST'])
def create_todo():
error = False
body = {}
try:
description = request.get_json()['description']
list_id = request.get_json()['list_id']
todo = Todo(description=description)
active_list = TodoList.query.get(list_id)
todo.list = active_list
db.session.add(todo)
db.session.commit()
body['description'] = todo.description
except:
error = True
db.session.rollback()
print(sys.exc_info())
finally:
db.session.close()
if not error:
return jsonify(body)
else:
abort(500)
Web app view
Error

I would try to put a more verbose exception in your code. Also, I think you can have the error check inside your try...accept
#app.route('/todos/create', methods=['POST'])
def create_todo():
body = {}
try:
description = request.get_json()['description']
list_id = request.get_json()['list_id']
todo = Todo(description=description)
active_list = TodoList.query.get(list_id)
todo.list = active_list
db.session.add(todo)
db.session.commit()
body['description'] = todo.description
return jsonify(body)
except Exception as e:
print(e) # ------- tracing
db.session.rollback()
print(sys.exc_info())
finally:
db.session.close()
abort(500)

Related

CSRF Token missing error while trying to update database with fetch

I'm trying to update the content of a database item using fetch. However, I get 403 Forbidden error in the console. I'm not using a form in my HTML template, just appending the elements to a div. The log says CSRF token missing.
document.addEventListener("DOMContentLoaded", function(){
const button = document.querySelectorAll("#edit_profile")
button.forEach(function(button){
button.onclick = function(){
const memberID = button.dataset.id;
const usernameID = button.dataset.username;
const username = document.getElementById(`username_${memberID}`);
let edit_username = document.createElement("textarea");
edit_username.setAttribute("rows", "1");
edit_username.innerHTML = username.innerHTML
edit_username.id = `edit_username_${memberID}`;
edit_username.className = `form-control username ${usernameID}`;
const saveButton = document.createElement("button");
saveButton.innerHTML = "Save";
saveButton.id = `saveButton_${memberID}`;
saveButton.className = "btn btn-success col-3";
saveButton.style.margin = "10px";
document.getElementById(`edit_${memberID}`).append(edit_username);
document.getElementById(`edit_${memberID}`).append(saveButton);
saveButton.addEventListener("click", function(){
edit_username = document.getElementById(`edit_username_${memberID}`);
fetch(`/edit_profile/${memberID}`,{
method: "POST",
body: JSON.stringify({
username: edit_username.value,
})
})
.then(response => response.json())
.then(result => {
console.log(result);
if(result[`error`]){
reset(memberID)
}
else {
username.innerHTML = result.username;
reset(memberID)
}
})
.catch(error => {
console.error(error);
})
})
}
});
I added the following decorator in views.py and it solved the problem:
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def edit_profile(request, member_id):
if request.method != "POST":
return JsonResponse({"error": "POST request required."}, status=400)
team_members = Team.objects.get(id = member_id)
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
username = body['username']
skills = body['skills']
bio = body['bio']
Team.objects.filter(id=member_id).update(username=f'{username}',skills=f'{skills}',bio=f'{bio}')
return JsonResponse({"message": "Successful", "username": username, "skills": skills, "bio": bio}, status=200)

The like of a user is being shown when the user removed their like in my program. How can I fix it?

To explain what I mean in the title, let me show you the output.
This is the like button counter when the user did not click on the like button:
This is the like button counter when the user clicked on the like button:
This is the like button counter when the user clicked on the like button again to remove their like:
The program I wrote seems to be kind of messed up. Here it is:
This is the route info for this particular page:
#app.route('/postlikes/<string:post_name>', methods=["GET","POST"])
def postlikes(post_name):
if request.method == "POST":
JSONdata = request.json
posts = Image.query.filter_by(post_name=post_name)
if JSONdata['is_liked'] == True:
for post in posts:
post.likes += 1
db.session.commit()
elif JSONdata['removed_like'] == True:
for post in posts:
post.likes = post.likes
db.session.commit()
else:
post = Image.query.filter_by(post_name=post_name).first()
return {"post_likes":post.likes}
#app.route('/hasliked/<string:post_name>', methods=['GET','POST'])
def hasliked(post_name):
post = Image.query.filter_by(post_name=post_name).first()
user = User.query.filter_by(username=current_user.username).first()
is_liked = posts_liked_by_users.query.filter_by(post_name=post_name).first()
if is_liked.post_name == post.post_name and is_liked.user_id == user.id:
return {"has_liked":True}
else:
return {"has_liked":False}
This is the JS involved in the program:
<script>
const likebtn = document.getElementById('likebtn');
const currentURL = window.location.href;
const likenum = document.getElementById('likenumber');
const postarray = currentURL.split("/");
const postName = postarray[4];
function setLikeBtnColor() {
likebtn.style.color = JSON.parse(localStorage.getItem('likebtn')) ? 'cornflowerblue':'black';
}
setLikeBtnColor();
async function current_color() {
const fetchData = await fetch('/hasliked/'+postName)
.then(response => response.json())
.then(function newdata(data) {
let strdata = JSON.stringify(data)
let JSONdata = JSON.parse(strdata)
return JSONdata
})
return fetchData
}
async function set_color() {
const jsondata = await current_color()
if (jsondata['has_liked'] === true) {
likebtn.style.color = 'cornflowerblue'
} else {
likebtn.style.color = 'black'
}
}
async function getLikeNumber() {
const fetchData = await fetch('/postlikes/'+postName)
.then(response => response.json())
.then(function getdata(data) {
let strdata = JSON.stringify(data)
let JSONdata = JSON.parse(strdata)
likenum.textContent = JSONdata.post_likes
return JSONdata.post_likes
})
return fetchData
}
async function displayLikes() {
let initialnum = await getLikeNumber()
likenum.innerHTML = initialnum
}
displayLikes()
async function myFunction() {
localStorage.setItem('likebtn', !JSON.parse(localStorage.getItem('likebtn')));
setLikeBtnColor();
if (likebtn.style.color === 'cornflowerblue') {
fetch('/postlikes/'+postName, {
method:"POST",
body: JSON.stringify({
removed_like: false,
liked_post:postName,
is_liked:true
}),
headers:{
"Content-type":"application/json; charset=UTF-8"
}
})
let currentLikeNum = await getLikeNumber();
likenum.innerHTML = currentLikeNum
} else {
fetch('/postlikes/'+postName, {
method:"POST",
body: JSON.stringify({
removed_like:true,
is_liked:false
}),
headers:{
"Content-type":"application/json; charset=UTF-8"
}
})
let currentLikeNum = await getLikeNumber();
likenum.innerHTML = currentLikeNum
}};
likebtn.addEventListener('click', myFunction);
</script>
This is the Image Table:
class Image(db.Model):
id = db.Column(db.Integer, primary_key=True)
title=db.Column(db.String(120), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow)
img_location = db.Column(db.String(600), nullable=False)
mimetype = db.Column(db.String(10))
post_name = db.Column(db.String(150),nullable=False, unique=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
manga_name = db.Column(db.String(100), unique=False, nullable=False)
likes = db.Column(db.Integer, nullable=False)
reports = db.Column(db.Integer, nullable=False)
number_of_comments = db.Column(db.Integer, nullable=False)
(Yes, I am very well aware of the fact that I should be using multiple tables but I have specifically intended to use one table, for now.)
The app was made using flask.
Please help me.
You add one like when the button that was clicked was a button with the color 'cornflowerblue'. It should add one when the button was black. Change it.
async function myFunction() {
.......
if (likebtn.style.color === 'cornflowerblue') {
........
}
........
}
to it
async function myFunction() {
.........
if (likebtn.style.color !== 'cornflowerblue') {
.........
}
........
}

How do you get the video data?

I want to take the video data and convert it using cv2. Which part is the video data? It's a code that might be related.
I want to send video data from the client to the server using webrtc, and convert and send the converted video from server to cv2 from the client again.
app.js
from flask import Flask, render_template, request, redirect, url_for, session
from flask_socketio import SocketIO, emit, join_room, leave_room
# Next two lines are for the issue: https://github.com/miguelgrinberg/python-engineio/issues/142
import os
secretKey = os.urandom(24)
app = Flask(__name__)
app.config['SECRET_KEY'] = secretKey
print("secretKey is ",secretKey)
socketio = SocketIO(app)
_users_in_room = {} # stores room wise user list
_room_of_sid = {} # stores room joined by an used
_name_of_sid = {} # stores display name of users
#app.route("/",methods=["GET", "POST"]) #첫번째 로그인화면
def loginPage():
if request.method == "POST":
room_id = request.form['room_id']
return redirect(url_for('enter_room',room_id=room_id))
return render_template("home.html")
#app.route("/<string:room_id>/checkpoint/", methods=["GET", "POST"]) #두번째 화면
def entry_checkpoint(room_id):
if request.method == "POST":
display_name = request.form['display_name']
mute_video = request.form['mute_video']
session[room_id] = {"name": display_name, "mute_video":mute_video}
return redirect(url_for("enter_room", room_id=room_id))
return render_template("chatroom_checkpoint.html", room_id=room_id)
#app.route("/<string:room_id>/") #세번째 스트림화면
def enter_room(room_id):
if room_id not in session:
return redirect(url_for("entry_checkpoint", room_id=room_id))
return render_template("chatroom.html", room_id=room_id, display_name=session[room_id]["name"], mute_video=session[room_id]["mute_video"])
#socketio.on("connect")
def on_connect():
sid = request.sid
print("New socket connected ", sid)
#socketio.on("join-room")
def on_join_room(data):
sid = request.sid
room_id = data["room_id"]
display_name = session[room_id]["name"]
# register sid to the room
join_room(room_id)
_room_of_sid[sid] = room_id
_name_of_sid[sid] = display_name
# broadcast to others in the room
print("[{}] New member joined: {}<{}>".format(room_id, display_name, sid))
emit("user-connect", {"sid": sid, "name": display_name}, broadcast=True, include_self=False, room=room_id)
# add to user list maintained on server
if room_id not in _users_in_room:
_users_in_room[room_id] = [sid]
emit("user-list", {"my_id": sid}) # send own id only
else:
usrlist = {u_id:_name_of_sid[u_id] for u_id in _users_in_room[room_id]}
emit("user-list", {"list": usrlist, "my_id": sid}) # send list of existing users to the new member
_users_in_room[room_id].append(sid) # add new member to user list maintained on server
print("\nusers: ", _users_in_room, "\n")
#socketio.on("disconnect")
def on_disconnect():
sid = request.sid
room_id = _room_of_sid[sid]
display_name = _name_of_sid[sid]
print("[{}] Member left: {}<{}>".format(room_id, display_name, sid))
emit("user-disconnect", {"sid": sid}, broadcast=True, include_self=False, room=room_id)
_users_in_room[room_id].remove(sid)
if len(_users_in_room[room_id]) == 0:
_users_in_room.pop(room_id)
_room_of_sid.pop(sid)
_name_of_sid.pop(sid)
print("\nusers: ", _users_in_room, "\n")
#socketio.on("data")
def on_data(data):
sender_sid = data['sender_id']
target_sid = data['target_id']
if sender_sid != request.sid:
print("[Not supposed to happen!] request.sid and sender_id don't match!!!")
if data["type"] != "new-ice-candidate":
print('{} message from {} to {}'.format(data["type"], sender_sid, target_sid))
socketio.emit('data', data, room=target_sid)
if __name__ == "__main__":
socketio.run(app, host='0.0.0.0', port='5050', debug=True)
chatroom_networking.js
var myID;
var _peer_list = {};
// socketio
var protocol = window.location.protocol;
var socket = io(protocol + '//' + document.domain + ':' + location.port, {autoConnect: false});
document.addEventListener("DOMContentLoaded", (event)=>{
startCamera();
});
var camera_allowed=false;
var mediaConstraints = {
audio: true, // We want an audio track
video: true
}
function startCamera()
{
navigator.mediaDevices.getUserMedia(mediaConstraints)
.then((stream)=>{
myVideo.srcObject = stream;
camera_allowed = true;
//start the socketio connection
socket.connect();
})
.catch((e)=>{
console.log("getUserMedia Error! ", e);
alert("Error! Unable to access camera or mic! ");
});
}
socket.on("connect", ()=>{
console.log("socket connected....");
socket.emit("join-room", {"room_id": myRoomID});
});
socket.on("disconnect", (data)=>{
console.log("disconnect");
});
socket.on("user-connect", (data)=>{
console.log("user-connect ", data);
let peer_id = data["sid"];
let display_name = data["name"];
_peer_list[peer_id] = undefined; // add new user to user list
addVideoElement(peer_id, display_name);
});
socket.on("user-disconnect", (data)=>{
console.log("user-disconnect ", data);
let peer_id = data["sid"];
closeConnection(peer_id);
removeVideoElement(peer_id);
});
socket.on("user-list", (data)=>{
console.log("user list recvd ", data);
myID = data["my_id"];
if( "list" in data) // not the first to connect to room, existing user list recieved
{
let recvd_list = data["list"];
// add existing users to user list
for(peer_id in recvd_list)
{
display_name = recvd_list[peer_id];
_peer_list[peer_id] = undefined;
addVideoElement(peer_id, display_name);
}
start_webrtc();
}
});
function closeConnection(peer_id)
{
if(peer_id in _peer_list)
{
_peer_list[peer_id].onicecandidate = null;
_peer_list[peer_id].ontrack = null;
_peer_list[peer_id].onnegotiationneeded = null;
delete _peer_list[peer_id]; // remove user from user list
}
}
function log_user_list()
{
for(let key in _peer_list)
{
console.log(`${key}: ${_peer_list[key]}`);
}
}
//---------------[ webrtc ]--------------------
var PC_CONFIG = {
iceServers: [
{
urls: ['stun:stun.l.google.com:19302',
'stun:stun1.l.google.com:19302',
'stun:stun2.l.google.com:19302',
'stun:stun3.l.google.com:19302',
'stun:stun4.l.google.com:19302'
]
},
]
};
function log_error(e){console.log("[ERROR] ", e);}
function sendViaServer(data){socket.emit("data", data);}
socket.on("data", (msg)=>{
switch(msg["type"])
{
case "offer":
handleOfferMsg(msg);
break;
case "answer":
handleAnswerMsg(msg);
break;
case "new-ice-candidate":
handleNewICECandidateMsg(msg);
break;
}
});
function start_webrtc()
{
// send offer to all other members
for(let peer_id in _peer_list)
{
invite(peer_id);
}
}
function invite(peer_id)
{
if(_peer_list[peer_id]){console.log("[Not supposed to happen!] Attempting to start a connection that already exists!")}
else if(peer_id === myID){console.log("[Not supposed to happen!] Trying to connect to self!");}
else
{
console.log(`Creating peer connection for <${peer_id}> ...`);
createPeerConnection(peer_id);
let local_stream = myVideo.srcObject;
local_stream.getTracks().forEach((track)=>{_peer_list[peer_id].addTrack(track, local_stream);});
}
}
function createPeerConnection(peer_id)
{
_peer_list[peer_id] = new RTCPeerConnection(PC_CONFIG);
_peer_list[peer_id].onicecandidate = (event) => {handleICECandidateEvent(event, peer_id)};
_peer_list[peer_id].ontrack = (event) => {handleTrackEvent(event, peer_id)};
_peer_list[peer_id].onnegotiationneeded = () => {handleNegotiationNeededEvent(peer_id)};
}
function handleNegotiationNeededEvent(peer_id)
{
_peer_list[peer_id].createOffer()
.then((offer)=>{return _peer_list[peer_id].setLocalDescription(offer);})
.then(()=>{
console.log(`sending offer to <${peer_id}> ...`);
sendViaServer({
"sender_id": myID,
"target_id": peer_id,
"type": "offer",
"sdp": _peer_list[peer_id].localDescription
});
})
.catch(log_error);
}
function handleOfferMsg(msg)
{
peer_id = msg['sender_id'];
console.log(`offer recieved from <${peer_id}>`);
createPeerConnection(peer_id);
let desc = new RTCSessionDescription(msg['sdp']);
_peer_list[peer_id].setRemoteDescription(desc)
.then(()=>{
let local_stream = myVideo.srcObject;
local_stream.getTracks().forEach((track)=>{_peer_list[peer_id].addTrack(track, local_stream);});
})
.then(()=>{return _peer_list[peer_id].createAnswer();})
.then((answer)=>{return _peer_list[peer_id].setLocalDescription(answer);})
.then(()=>{
console.log(`sending answer to <${peer_id}> ...`);
sendViaServer({
"sender_id": myID,
"target_id": peer_id,
"type": "answer",
"sdp": _peer_list[peer_id].localDescription
});
})
.catch(log_error);
}
function handleAnswerMsg(msg)
{
peer_id = msg['sender_id'];
console.log(`answer recieved from <${peer_id}>`);
let desc = new RTCSessionDescription(msg['sdp']);
_peer_list[peer_id].setRemoteDescription(desc)
}
function handleICECandidateEvent(event, peer_id)
{
if(event.candidate){
sendViaServer({
"sender_id": myID,
"target_id": peer_id,
"type": "new-ice-candidate",
"candidate": event.candidate
});
}
}
function handleNewICECandidateMsg(msg)
{
console.log(`ICE candidate recieved from <${peer_id}>`);
var candidate = new RTCIceCandidate(msg.candidate);
_peer_list[msg["sender_id"]].addIceCandidate(candidate)
.catch(log_error);
}
function handleTrackEvent(event, peer_id)
{
console.log(`track event recieved from <${peer_id}>`);
if(event.streams)
{
getVideoObj(peer_id).srcObject = event.streams[0];
}
}
chatroom_ui.js
var myVideo;
document.addEventListener("DOMContentLoaded", (event)=>{
myVideo = document.getElementById("local_vid");
document.getElementById("room_link").innerHTML=`or the link: <span class="heading-mark">${window.location.href}</span>`;
});
function makeVideoElement(element_id, display_name)
{
let wrapper_div = document.createElement("div");
let vid_wrapper = document.createElement("div");
let vid = document.createElement("video");
let name_text = document.createElement("div");
wrapper_div.id = "div_"+element_id;
vid.id = "vid_"+element_id;
wrapper_div.className = "shadow video-item";
vid_wrapper.className = "vid-wrapper";
vid.autoplay = true;
vid_wrapper.appendChild(vid);
wrapper_div.appendChild(vid_wrapper);
console.log(wrapper_div)
return wrapper_div;
}
function addVideoElement(element_id)
{
document.getElementById("video_grid").appendChild(makeVideoElement(element_id));
}
function removeVideoElement(element_id)
{
let v = getVideoObj(element_id);
if(v.srcObject){
v.srcObject.getTracks().forEach(track => track.stop());
}
v.removeAttribute("srcObject");
v.removeAttribute("src");
document.getElementById("div_"+element_id).remove();
}
function getVideoObj(element_id)
{
return document.getElementById("vid_"+element_id);
}

Can't read value of dynamically generated HTML objects

Datos() loads info converted to HTML objects into an HTML file with the class of each one already defined. I need save() to read the values of the inputs generated but when I try to do it using document.querySelector() to find them by their class, it apparently returns null and gives me this error:
infoPersonal.js:67 Uncaught TypeError: Cannot read property 'value' of null
at HTMLSpanElement. (infoPersonal.js:67)
Am I doing something wrong?
(I would add a snippet code but it doesn't work because of some imports, I hope the javascript code is enough)
const datos = () => {
const token = localStorage.getItem('token')
if (token) {
return fetch('https://janfa.gharsnull.now.sh/api/auth/me', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
authorization: token,
},
})
.then(x => x.json())
.then(user => {
const datalist = document.querySelectorAll(".data")
datalist.forEach(function(el) {
var divInfo = document.createElement("div")
divInfo.setAttribute("class", `divInfo-${el.getAttribute("data-target")}`)
var divInput = document.createElement("div")
divInput.setAttribute("class", `divInput-${el.getAttribute("data-target")}`)
divInput.hidden = true
var input
var icon
const template = '<p>' + user[el.getAttribute("data-target")] + '</p>'
input = document.createElement("input")
input.type = "text"
input.setAttribute("class", `input-${el.getAttribute("data-target")}`)
input.value = user[el.getAttribute("data-target")]
icon = document.createElement("span")
icon.setAttribute("class", "flaticon-diskette")
icon.setAttribute("data-target", `${el.getAttribute("data-target")}`)
divInfo.innerHTML = template
divInput.appendChild(input)
divInput.appendChild(icon)
el.appendChild(divInfo)
el.appendChild(divInput)
}
})
}).then(() => {
save()
})
}
}
const save = () => {
const saves = document.querySelectorAll(".flaticon-diskette")
saves.forEach(function(save) {
const input = document.querySelector(`.input-${save.getAttribute("data-target")}`)
save.addEventListener('click', () => {
console.log(input.value)
})
})
}
That's the corrected script, have a good day!
const datos= () => {
const token = localStorage.getItem('token')
if (token) {
return fetch('https://janfa.gharsnull.now.sh/api/auth/me', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
authorization : token,
},
})
.then( x => x.json())
.then( user =>{
const datalist = document.querySelectorAll(".data")
datalist.forEach( function(el){
var divInfo= document.createElement("div")
divInfo.setAttribute("class", `divInfo-${el.getAttribute("data-target")}`)
var divInput = document.createElement("div")
divInput.setAttribute("class", `divInput-${el.getAttribute("data-target")}`)
divInput.hidden= true
var input
var icon
const template = '<p>' + user[el.getAttribute("data-target")] + '</p>'
input = document.createElement("input")
input.type = "text"
input.setAttribute("class" , `input-${el.getAttribute("data-target")}`)
input.value = user[el.getAttribute("data-target")]
icon = document.createElement("span")
icon.setAttribute("class", "flaticon-diskette")
icon.setAttribute("data-target", `${el.getAttribute("data-target")}`)
divInfo.innerHTML = template
divInput.appendChild(input)
divInput.appendChild(icon)
el.appendChild(divInfo)
el.appendChild(divInput)
}
})
}).then (() =>{
save()
})
}
}
const save = () =>{
const saves= document.querySelectorAll(".flaticon-diskette")
saves.forEach(function(save){
const input = document.querySelector(`.input-${save.getAttribute("data-target")}`)
save.addEventListener('click', () =>{
console.log(input.value)
})
})
}

Django Saving and loading messages

i am making chat app using django, and i follow the tutorial in youtube and documentation and i follow everything they say, but i still get the error
chat/
__init__.py
consumers.py
routing.py
templates/
urls.py
views.py
This is my code in consumers.py
this is the script in my room.html, i already have script in ReconnectingWebSocket.js
<script>
var roomName = {{ room_name_json }};
var username = {{ username }};
var chatSocket = new ReconnectingWebSocket(
'ws://' + window.location.host +
'/ws/chat/' + roomName + '/');
chatSocket.onmessage = function(e) {
var data = JSON.parse(e.data);
var message = data['message'];
var author = message['author'];
var msgListTag = document.createElement('li');
var pTag = document.createElement('p');
pTag.textContent = message.content;
if (author === username){
msgListTag.className='sent';
}
else{
msgListTag.className = 'replies';
}
msgListTag.appendChild(pTag);
document.querySelector('#chat-log').appendChild(msgListTag);
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function(e) {
var messageInputDom = document.getElementById('#chat-message-input');
var message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'command': 'new_message',
'message': message,
'from': username
}));
messageInputDom.value = '';
};
</script>
class ChatConsumer(WebsocketConsumer):
def fetch_messages(self, data):
messages = Message.last_10_messages()
content = {
'messages': self.messages_to_json(messages)
}
self.send_message(content)
def new_message(self, data):
author = data['from']
author_user =User.objects.filter(username=author)[0]
message = Message.objects.create(
author=author_user,
content=data['message']
)
content = {
'command': 'new_message',
'message': self.messages_to_json(message)
}
return self.send_chat_message(content)
def messages_to_json(self, messages):
result = []
for message in messages:
result.append(self.message_to_json(message))
return result
def message_to_json(self, message):
return {
'author':message.author.username,
'content': message.content,
'timestamp': str(message.timestamp)
}
commands = {
'fetch_messages': fetch_messages,
'new_message': new_message
}
def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
def disconnect(self, close_code):
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
def receive(self, text_data):
data = json.loads(text_data)
self.commands[data['command']](self, data)
def send_chat_message(self, message):
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
def send_message(self, message):
self.send(text_data=json.dump(message))
def chat_message(self, event):
message = event['message']
self.send(text_data=json.dump(message))
my views.py
return render(request, 'chat/room.html', {
'room_name_json': mark_safe(json.dumps(room_name)),
'username':mark_safe(json.dumps(request.user.username)),
})
my models.py
class Message(models.Model):
author = models.ForeignKey(User, related_name='author_messages', on_delete=models.CASCADE)
content = models.TextField(null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True,null=True, blank=True)
def __str__(self):
return self.author.username
def last_10_messages(self):
return Message.objects.order_by('-timestamp').all()[:10]
this is the error i get
i get error from this line
def messages_to_json(self, messages):
result = []
for message in messages:
result.append(self.message_to_json(message))
return result
for message in messages:
UPDATE when i tried this
def messages_to_json(self, messages):
content = {
'command': 'new_message',
'message': self.message_to_json(messages)
}
I get this error
your messages instance is not iterable,so you cannot use it in for loop,it is an instance of your Messages model that inherit from models.Model that is not an iterable,so you can simply use your message_to_json function:
content = {
'command': 'new_message',
'message': self.message_to_json(message)
}

Categories