老师,我在写本节课后作业中的私信功能的通知时,我把通知处理器写在如下发送私信函数中的倒数第三行:
@login_required
@ajax_required
@require_http_methods(["POST"])
def send_message(request):
sender = request.user
recipient_username = request.POST["to"]
recipient = get_user_model().objects.get(username=recipient_username)
message = request.POST["message"]
if len(message.strip()) != 0 and sender != recipient:
msg = Message.objects.create(
sender=sender,
recipient=recipient,
message=message
)
channel_layer = get_channel_layer()
payload = {
'type': 'receive',
'message': render_to_string('messager/single_message.html', {'message': msg}),
'sender': sender.username
}
async_to_sync(channel_layer.group_send)(recipient_username, payload)
notification_handler(sender, recipient, 'R', msg)
return render(request, 'messager/single_message.html', {"message": msg})
return HttpResponse()
但是测试报错:
'action_object': action_object.user.username,
AttributeError: 'Message' object has no attribute 'user'
通知处理器的代码与您后来修复bug后的代码一致:
def notification_handler(actor, recipient, verb, action_object, **kwargs):
key = kwargs.get('key', 'notification')
id_value = kwargs.get('id_value', None)
Notification.objects.create(
actor=actor,
recipient=recipient,
verb=verb,
action_object=action_object
)
channel_layer = get_channel_layer()
payload = {
'type': 'receive',
'key': key,
'actor_name': actor.username,
'action_object': action_object.user.username,
'id_value': id_value
}
async_to_sync(channel_layer.group_send)('notifications', payload)
也就是说'action_object': action_object.user.username这行代码走不通,虽然说私信模型类中确实没有user字段,只有sender和recipient。也有可能是我的第四个参数action_object写错了,但是我看了半天确实应该是msg呀,麻烦老师指点一下。