The intention of this project is to make a Chat Room. I have 2 tables, Django's predefined User table and Message table, where messages sent by users are stored.
I want a user to send a message, via a form sent to the table by the sendMessage () method (Javascript function) with the REST Framework API feature.
The problem I encounter is that I can not receive the username of the currently logged-in user and send it as input to save to the database.
When executing my program I also noticed that the value received in the normaluser sendMessage () function is equal to "". Also when adding a message through the API, I noticed that I was only able to add when I removed the following line of code, which showed in JSON format the normaluser field as an integer (user.id) and not as a string (user.username).
Code line referenced:
class MessageSerializer(serializers.ModelSerializer):
normaluser = MessageUserSerializer(many=False, read_only=True) <- Esta linha
class Meta:
model = Message
fields = ('id', 'body', 'normaluser',)
Form (HTML):
<form method="post" id="msg">
<div class="form-group">
{% csrf_token %}
<label for="comment">Message:</label>
<input name="body"></input>
<input name="normaluser" hidden value= {{ normaluser.id }}></input>
</div>
{{ form.as_p }}
<button type="submit" onclick="sendMessage()">Enter</button>
</form>
sendMessage (Javascript):
function sendMessage() {
var form = document.getElementById("msg");
var csrf_token = jQuery("input[name=csrfmiddlewaretoken]").val();
var req = new XMLHttpRequest();
var url = '/website/message/';
var method = "POST";
var data = {body: form.body.value,
normaluser: form.normaluser.value,};
req.open(method, url);
req.setRequestHeader("X-CSRFToken", csrf_token);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json");
req.addEventListener("load", function () {
console.log(this.responseText);
getMessages();
});
req.send(JSON.stringify(data));
console.log(data);
}