You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Django好友请求接受视图中的HttpRequest AssertionError?

Django好友请求接受时的HttpRequest断言错误解决

问题描述

接受好友请求时触发以下错误:

AssertionError: The `request` argument must be an instance of `django.http.HttpRequest`, not `userauths.models.User`.
[28/May/2024 16:09:33] "GET /accept-friend-request/?id=8 HTTP/1.1" 500 121207

关联API路由:

path("accept-friend-request/", views.accept_friend_request, name="accept-friend-request"),

对应的视图函数:

@api_view(['GET'])
@login_required
def accept_friend_request(request):
    if request.method == 'GET':
        sender_id = request.GET.get('id')
        receiver = request.user

        # Log the sender_id
        logger.debug(f"Sender ID: {sender_id}")

        try:
            # Retrieve the sender user from the database
            sender = User.objects.get(id=sender_id)

            # Retrieve the sender's profile
            sender_profile = sender.profile

            # Add sender's profile to receiver's friends and vice versa
            receiver.profile.friends.add(sender_profile)
            sender_profile.friends.add(receiver.profile)

            # Delete the friend request
            friend_request = FriendRequest.objects.filter(receiver=receiver, sender=sender).first()
            friend_request.delete()

            # Send notification
            send_notification(sender, receiver, None, None, noti_friend_request_accepted)

            data = {
                "message": "Accepted",
                "bool": True,
            }
            return JsonResponse({'data': data})
        except User.DoesNotExist:
            logger.error(f"User with ID {sender_id} does not exist.")
            return JsonResponse({'error': 'User does not exist.'}, status=404)
    else:
        return JsonResponse({'error': 'Only GET requests are allowed.'})

问题

如何解决该场景下的HttpRequest相关AssertionError?

已尝试操作

  • 日志确认sender_id获取正常
  • 验证sender.profile和receiver.profile可正常访问
  • 确认数据库中用户和好友请求记录存在

预期行为

好友请求被接受,双方互相添加至好友列表,成功发送通知且无AssertionError。


解决方案

错误根源在于send_notification函数的调用参数不符合要求:

  1. 检查send_notification的参数定义:查看该函数的代码,确认它的第一个参数是否要求传入django.http.HttpRequest实例。
  2. 修正调用参数:
    错误调用中你传入的第一个参数是sender(User实例),而函数预期的是HttpRequest对象。调整调用语句,将视图中的request对象传入,同时根据函数定义调整后续参数顺序。例如:
    # 假设send_notification定义为def send_notification(request, recipient, actor, ...)
    send_notification(request, sender, receiver, None, noti_friend_request_accepted)
    
    (具体参数顺序需匹配send_notification的实际参数列表,比如如果函数需要接收通知的用户是receiver,就对应调整位置)

如果send_notification函数本身不需要HttpRequest参数,而是参数名写错(比如把sender写成了request),则需要修改函数的参数定义,将错误的参数名改为正确的名称(如sender)。

内容的提问来源于stack exchange,提问作者Previn Bogopa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 09:22:47