ValueError: Cannot assign "(<User: testuser>,)": "Message.user" must be a "User" instance
ValueError: Cannot assign "(<User: testuser>,)": "Message.user" must be a "User" instance
尝试创建一个具有多个聊天室的简单实时聊天应用程序。尝试在消息模型中添加新消息时,出现 ValueError。
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)
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!")
我见过很多类似的问题,但是 none 的解决方案有效。
谢谢。
由于您在以下行中添加了尾随逗号
user = User.objects.get(username = request.POST['username']),
room = Room.objects.get(id = request.POST['room_id']),
message = request.POST['message'],
这些变量变成 python tuple
并导致错误,因为值的类型错误。
删除尾随的逗号应该可以解决问题。
user = User.objects.get(username = request.POST['username'])
room = Room.objects.get(id = request.POST['room_id'])
message = request.POST['message']
尝试创建一个具有多个聊天室的简单实时聊天应用程序。尝试在消息模型中添加新消息时,出现 ValueError。
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)
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!")
我见过很多类似的问题,但是 none 的解决方案有效。
谢谢。
由于您在以下行中添加了尾随逗号
user = User.objects.get(username = request.POST['username']),
room = Room.objects.get(id = request.POST['room_id']),
message = request.POST['message'],
这些变量变成 python tuple
并导致错误,因为值的类型错误。
删除尾随的逗号应该可以解决问题。
user = User.objects.get(username = request.POST['username'])
room = Room.objects.get(id = request.POST['room_id'])
message = request.POST['message']