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

WSGIRequest对象无request属性:上下文处理器函数调用异常排查

问题分析与解决

首先明确:Django的上下文处理器函数不需要接收self作为参数,正确的参数是request对象。你写的两个函数都用了self,这本身就是错误的。之所以get_user没报错,大概率是该函数的返回值没被模板实际引用,或者存在缓存、匿名用户访问等偶然情况;而get_last_10_messages被实际调用,触发了参数不匹配的错误——因为Django会把WSGIRequest对象传给上下文处理器,而非类实例,所以self.request自然不存在。

修正后的代码

from message.models import Message
from contact.models import Contact

def get_last_10_messages(request):
    # 直接使用request对象,无需self
    if not request.user.is_authenticated:
        return {'last_messages': []}
    user = Contact.objects.get(user_id=request.user.id).select_related('organization')
    # 补充根据用户所属组织过滤消息的逻辑
    last_10_messages = Message.objects.filter(organization=user.organization).order_by('-created_at')[:10]
    return {'last_messages': last_10_messages}

def get_user(request):
    if not request.user.is_authenticated:
        return {'user': None}
    user = Contact.objects.get(user_id=request.user.id).select_related('organization')
    return {'user': user}

额外注意事项

  • 必须处理用户未登录的场景,否则匿名用户访问会抛出Contact.DoesNotExist异常。
  • 上下文处理器需要在settings.py的TEMPLATES['OPTIONS']['context_processors']中注册,才能在模板中全局调用返回的变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:25:20