在Django视图和模板中调用当前用户

时间:2019-05-01 21:55:33

标签: python django django-views

我有一个视图,其中两个用户之间创建了一个聊天频道。我想在发送消息时通知用户(消息的来源),但是我在访问当前用户(登录并发送消息的用户)时遇到问题。在下面的视图中,我有一个“ to_user”,其名称显示正确,但是,“ current_user”未显示。

这是我的观点。py

@login_required
def create_channel(request, to_user_id):
    to_user = get_user_model().objects.get(pk=to_user_id)
    try:
        channel = Channel.objects.get(users=request.user, users__id=to_user_id)
    except Channel.DoesNotExist:
        channel = Channel.objects.create(
            channel_name='{from_user}-{to_user}'.format(from_user=request.user.username, to_user=to_user)
        )
        channel.users.add(request.user)
        channel.users.add(to_user)
        client = get_client()
        service = client.chat.services(settings.TWILIO_CHAT_SID)
        twilio_channel = service.channels.create(channel.channel_name)

        channel.twilio_chat_id = twilio_channel.sid

        twilio_channel.members.create(identity=request.user.get_twilio_user_id())
        twilio_channel.members.create(identity=to_user.get_twilio_user_id())
        channel.save()
        #email the to_user when they receive a message
        to_user = to_user
        current_user = request.user
        to_user_email = to_user.email
        user_email = current_user.email
        html_message_to_user = render_to_string('send_message_to_user.html', {'user': current_user,
                                                                            'to_user': to_user,
                                                                            'channel': channel,
                                                                            }
        #send email to the to_user
        send_mail(current_user.first_name + ' has sent you a message', plain_message_to_user, 'x@x.com', [to_user_email], fail_silently=False, html_message=html_message_to_user)
        mail_admins('A message has been sent', 'A message has been sent to ' + to_user.first_name + ' from ' + current_user.first_name, fail_silently=False, )

    return HttpResponseRedirect(reverse('chatapp:twilio', kwargs={'pk': channel.pk}))

电子邮件已正确发送,但是未显示“当前用户”的名字。我也尝试过简单地放入“ user”或“ request.user”,而这些都不起作用。我不确定如何获取当前用户名以显示在电子邮件或电子邮件模板中。

任何帮助表示赞赏!

0 个答案:

没有答案