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

Django使用get_user_model时报'function' object has no attribute 'objects'错误如何解决

报错根源

你代码里导入的get_user_model是Django提供的函数,需要主动调用才能返回项目配置的用户模型类,你直接调用get_user_model.objects相当于在函数对象上访问objects属性,自然会触发属性不存在的报错。

修复步骤
  1. 修改views.py中获取用户的代码,先调用get_user_model()拿到用户模型类,再执行查询
  2. 补充get()方法的异常捕获:Django的ORM get()方法查询不到结果时会抛出DoesNotExist异常,你原代码里写的if details is None永远不会触发,必须用异常捕获处理用户不存在的场景

修复后的完整views.py代码如下:

from django.contrib.auth import get_user_model
from django.shortcuts import render, redirect

def otp_login(request):
    if request.method == 'POST':
        phones = request.POST['phone']
        print(phones)
        # 先调用get_user_model()函数拿到用户模型类,再查询
        User = get_user_model()
        try:
            details = User.objects.get(phone=phones)
        # 捕获用户不存在的异常
        except User.DoesNotExist:
            return render(request, "otp_login.html", {'msg': "No user registered with this mobile number."})
        print(details)
        request.session['phone']=phones
        return redirect('otp')
    return render(request, "otp_login.html")
额外注意事项
  • 你当前直接从request.POST取phone参数,如果请求没传这个字段会触发MultiValueDictKeyError,建议用request.POST.get('phone', '')更安全
  • 要确保你自定义的用户模型里确实有phone字段,否则查询时会触发字段不存在的报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:15:03