Как настроить сообщение об ошибке пользователя in_active для rest_framework_simplejwt в Django

Я установил модель нескольких пользователей в Django rest framework и использую dj_rest_auth, allauth и djangosimplejwt для моего рабочего процесса аутентификации и авторизации пользователей

мой serialisers.py выглядит следующим образом

и мой views.py выглядит следующим образом


class Login(LoginView):
    """
    Check the credentials and return the REST Token
    if the credentials are valid and authenticated.
    Calls Django Auth login method to register User ID
    in Django session framework

    Accept the following POST parameters: username, password
    Return the REST Framework Token Object's key.
    """

    serializer_class = LoginSerializer

    def post(self, request, *args, **kwargs):
        self.request = request
        self.serializer = self.get_serializer(data=self.request.data)
        self.serializer.is_valid(raise_exception=True)

        self.login()
        return self.get_response()

    def get_all_clients(self):
        """
        Using related objects, get all clients of the business
        """
        business = self.request.user
        business_client = ClientProfile.objects.filter(business=business)

        client_list = business_client.values(
            'client__id',
            'client__email',
            'client__fullname',
            'logo',
        )

        # rename the keys in clean_names
        for client in client_list:
            client['id'] = client.pop('client__id')
            client['email'] = client.pop('client__email')
            client['fullname'] = client.pop('client__fullname')
            client['logo'] = (
                f"{self.request.META['HTTP_HOST']}{business.profile_image.url}"
                if client['logo']
                else None
            )

        return client_list

    # display user profile information based on type of user
    def get_response(self):
        response = super().get_response()
        user = self.request.user

        if user.type.name == "Business":

            profile = {
                'profile': {
                    'business_logo': f"{self.request.META['HTTP_HOST']}{user.businessprofile.logo.url}"
                    if user.businessprofile.logo
                    else None,
                    'business_name': user.businessprofile.business_name,
                    'user_type': user.type.name,
                    'client_list': self.get_all_clients(),
                }
            }
            response.data.update(profile)
            return response

        elif user.type.name == 'Client':

            profile = {
                'profile': {
                    'logo': (
                        f"{self.request.META['HTTP_HOST']}{user.clientprofile.logo.url}"
                    )
                    if user.clientprofile.logo
                    else None,
                    'name': user.clientprofile.client_business_name,
                    'type': user.type.name,
                    'full_name': user.fullname,
                    'country': user.country.name,
                }
            }
            response.data.update(profile)

        return response

Первое, что я заметил, это когда пользователь имеет неактивный аккаунт, т.е. user.is_active Я хочу написать более осмысленное сообщение, чтобы облегчить фронтенд, но когда я использую просматриваемый api, я получаю

{
  "error": [
    "Unable to log in with provided credentials."
  ]
}

и когда я использую postman, я получаю 401 ошибку словаря

{
  "detail": "User is inactive",
  "code": "user_inactive"
}

вышеуказанная ошибка возникает, когда я использую документацию dj_rest_auth, которая говорит, что я должен добавить

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'dj_rest_auth.jwt_auth.JWTCookieAuthentication',
    ),
    
}

Но если я следую документации Django simplejwt, в ней говорится

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
       )
}

Я получаю это только на postman и на просматриваемом api endpoint

{
  "error": [
    "Unable to log in with provided credentials."
  ]
}

Я буду благодарен, если смогу получить действенный способ получить правильное сообщение об ошибке, которое мне нужно, и небольшое объяснение, почему существуют различные коды ошибок и документация по использованию этого

Вернуться на верх