【问题标题】:hi, I am using Django Framework I want to check if the mobile-no is in the database or not but I have error嗨,我正在使用 Django Framework 我想检查 mobile-no 是否在数据库中但是我有错误
【发布时间】:2023-01-09 21:02:30
【问题描述】:

我正在使用 Django Framework 我想检查 mobile-no 是否在数据库中但是当我运行代码时我有错误它只给我 False 即使数据库中存在数字它给我 False 有人可以帮助我这是我的代码

视图.py

@csrf_exempt
def forget_password(request):
    mobile_no = request.POST.get('mobile_no')
    # verify = models.User.objects.all()
    # verify = models.User.objects.filter(mobile_no=mobile_no).first()
    verify = models.User.objects.filter(mobile_no=mobile_no).exists()
    if verify:
        return JsonResponse({'bool':True})
    else:
        return JsonResponse({'bool':False,'msg' : 'mobile_no does not exist!!'})

【问题讨论】:

  • 这可能是类型转换问题,请检查手机号码的类型是否来自 DRF。
  • 我不知道为什么它对我不起作用

标签: django django-models django-rest-framework django-views


【解决方案1】:

作为手机号对于每个用户都是唯一的,请使用以下视图:


@csrf_exempt
def forget_password(request):
    mobile_no = request.POST.get('mobile_no')
    try:    
        models.User.objects.get(mobile_no=mobile_no)
        return JsonResponse({'bool':True})
    except models.User.DoesNotExist:
        return JsonResponse({'bool':False,'msg' : 'mobile_no does not exist!!'}) 

【讨论】:

  • 它不起作用 我不知道它为什么不起作用
  • @BawarRwandzy 你能分享你的 html 吗,也许你应该使用 @required_post 装饰器。
【解决方案2】:

试试这段代码我认为你在导入用户模型时犯了一个错误

from django.contrib.auth.models import User
@csrf_exempt
def forget_password(request):
    mobile_no = request.POST.get('mobile_no')
    verify = User.objects.filter(mobile_no=mobile_no)
    if verify.exists():
        return JsonResponse({'bool':True})
    else:
        return JsonResponse({'bool':False,'msg' : 'mobile_no does not exist!!'})

【讨论】:

    猜你喜欢
    • 2013-03-31
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2021-09-11
    • 2014-08-24
    • 2019-01-13
    • 1970-01-01
    • 2021-08-17
    相关资源
    最近更新 更多