在Django中无法调用TypeError'bool'对象

问题描述

我正在使用Django中的simple-jwt模块实现登录功能。目前,只有通过电子邮件验证的用户才能登录,并且该条件语句中出现以下错误

在Django中无法调用TypeError'bool'对象

我不知道为什么不能输入布尔型变量。如何解决错误?这是我的代码

views.py

from .models import User
from .utils import Util
from .serializers import customregisterSerializer,customLoginSerializer,customTokenRefreshSerializer,userProfileSerializer
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import GenericAPIView
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.views import TokenObtainPairView,TokenRefreshView
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from django.urls import reverse
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
import jwt

class customSignUpView (GenericAPIView) :
    serializer_class = customregisterSerializer

    def post (self,request) :
        user = request.data
        serializer = self.serializer_class(data=user)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        user = User.objects.get(email=serializer.data['email'])

        token = RefreshToken.for_user(user).access_token

        current_site = get_current_site(request).domain
        relativeLink = reverse('emailVerify')
        
        absurls = F'http://{current_site}{relativeLink}?token={token}'
        email_body = F'Hi {user.username} Use link below to verify your email \n{absurls}'
        data = {'email_body': email_body,'to_email': user.email,'email_subject': 'Verify your email'}
        Util.send_email(data)
        
        return Response({'message': '이메일을 확인하세요'},status=201)

class customLoginView (GenericAPIView) :
    serializer_class = customLoginSerializer

    def post (self,request) :
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        try :
            user = User.objects.get(email=serializer.data['email'])

        except User.DoesNotExist :
            return Response({'message': '아이디 또는 비밀번호를 확인해주세요.'},status=401)

        if not user.is_verified() :
            return Response({'message': '이메일 인증을 먼저 해주세요.'},status=401)

        token = RefreshToken.for_user(user)

        data = {
            'token_type': 'Bearer','access_token': str(token.access_token),'expired_at': str(datetime.Now() + timedelta(hours=6)),'refresh_token': str(token),'refresh_token_expires_at': str(datetime.Now() + timedelta(days=30))
        }

        return Response(data,status=200)

class customrefreshView (TokenRefreshView) :
    serializer_class = customTokenRefreshSerializer

class VerifyEmail (GenericAPIView) :

    def get (self,request) :
        token = request.GET.get('token')

        try :
            payload = jwt.decode(token,settings.SECRET_KEY)
            user = User.objects.get(id=payload['user_id'])
            if not user.is_verified :
                user.is_verified = True
                user.save()
            return Response({'message': '성공적으로 인증되었습니다'})

        except jwt.ExpiredSignatureError :
            return Response({'message': '인증이 만료되었습니다'},status=400)
        
        except jwt.exceptions.DecodeError :
            return Response({'message': '잘못된 토큰입니다'},status=400)

class userProfileView (ModelViewSet) :
    serializer_class = userProfileSerializer
    permission_classes = [IsAuthenticated]

    def list (self,request) :
        queryset = User.objects.filter(email=self.request.user)
        serializer = userProfileSerializer(queryset,many=True)

        for i in serializer.data :
            return Response(i)

追踪

Traceback (most recent call last):
  File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\django\core\handlers\exception.py",line 34,in inner
    response = get_response(request)
  File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\django\core\handlers\base.py",line 115,in _get_response
    response = self.process_exception_by_middleware(e,request)
  File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\django\core\handlers\base.py",line 113,in _get_response
    response = wrapped_callback(request,*callback_args,**callback_kwargs)
  File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\django\views\decorators\csrf.py",line 54,in wrapped_view
    return view_func(*args,**kwargs)
  File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\django\views\generic\base.py",line 71,in view
    return self.dispatch(request,*args,**kwargs)
  File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\rest_framework\views.py",line 505,in dispatch
    response = self.handle_exception(exc)
  File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\rest_framework\views.py",line 465,in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\rest_framework\views.py",line 476,in raise_uncaught_exception
    raise exc
  File "C:\Users\kurak\AppData\Local\Programs\Python\python38-32\lib\site-packages\rest_framework\views.py",line 502,in dispatch
    response = handler(request,**kwargs)
  File "D:\school\대회 및 프로젝트\CoCo\api\views.py",line 50,in post
    if not user.is_verified() :
TypeError: 'bool' object is not callable

解决方法

user.is_verified 返回的是布尔值,因此您不必使用 paranethesis -> ()

应为

if not user.is_verified:
    return Response({'message': '이메일 인증을 먼저 해주세요.'},status=401)
,

您必须编写此代码

if not user.is_verified() :

不是

if not user.is_verified :