Trying to create a simple real-time chat application with multiple chat rooms. When trying to add new message in the message model, getting ValueError.
The model.py
:
class Message(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
room = models.ForeignKey(Room, on_delete=models.CASCADE)
body = models.TextField()
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
The view.py
:
def addMessage(request):
user = User.objects.get(username = request.POST['username']),
room = Room.objects.get(id = request.POST['room_id']),
message = request.POST['message'],
Message.objects.create(
user = user,
room = room,
body = message
)
return HttpResponse("Message Sent Sucessfully!")
I have seen many similar questions, but none of the solutions worked.
Thanks.
CodePudding user response:
Since you added trailing commas in the following lines
user = User.objects.get(username = request.POST['username']),
room = Room.objects.get(id = request.POST['room_id']),
message = request.POST['message'],
These variables become a python tuple
and result in the error since the values are wrong types.
Remove those trailing commas should fix the issue.
user = User.objects.get(username = request.POST['username'])
room = Room.objects.get(id = request.POST['room_id'])
message = request.POST['message']