phone number validator
This commit is contained in:
parent
6165a951df
commit
8fe2cb86aa
3 changed files with 54 additions and 2 deletions
|
|
@ -67,6 +67,7 @@ MIDDLEWARE = [
|
|||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
'utils.exceptions.ErrorMiddleware',
|
||||
]
|
||||
|
||||
# Tell Django OAuth Toolkit to use the Gooyal Application model
|
||||
|
|
@ -120,7 +121,8 @@ REST_FRAMEWORK = {
|
|||
'DEFAULT_THROTTLE_RATES': {
|
||||
'otp_min': '1/min',
|
||||
'otp_day': '20/day',
|
||||
}
|
||||
},
|
||||
'EXCEPTION_HANDLER': 'utils.exceptions.exception_handler',
|
||||
}
|
||||
|
||||
SPECTACULAR_SETTINGS = {
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ from apps.users.models import User
|
|||
from django.utils import timezone
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
phone_number_validator = RegexValidator(regex=r'^\+98\d{10,10}$', message=_(
|
||||
phone_number_validator = RegexValidator(regex=r'^\+98[1-9]\d{10}$', message=_(
|
||||
"Phone number must be entered in the format: '+989999999999'."
|
||||
),)
|
||||
class PublicUserSerializer(serializers.ModelSerializer):
|
||||
|
|
|
|||
50
utils/exceptions.py
Normal file
50
utils/exceptions.py
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import logging
|
||||
|
||||
from rest_framework.exceptions import APIException
|
||||
from rest_framework.views import exception_handler as drf_exception_handler
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
def exception_handler(exc, context):
|
||||
# پاسخ پیشفرض DRF را دریافت میکنیم
|
||||
response = drf_exception_handler(exc, context)
|
||||
|
||||
if response is not None:
|
||||
# ساختار دلخواه خود را تعریف میکنیم
|
||||
response_data = {
|
||||
'success': False,
|
||||
'status_code': response.status_code,
|
||||
'message': 'An error occurred',
|
||||
'details': {}
|
||||
}
|
||||
|
||||
if isinstance(exc, APIException):
|
||||
response_data['message'] = exc.detail if isinstance(exc.detail, str) else "Validation error"
|
||||
response_data['details'] = exc.detail if isinstance(exc.detail, dict) else {}
|
||||
|
||||
response.data = response_data
|
||||
|
||||
return response
|
||||
|
||||
|
||||
# در فایل middleware.py
|
||||
from django.http import JsonResponse
|
||||
|
||||
class ErrorMiddleware:
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
|
||||
def __call__(self, request):
|
||||
response = self.get_response(request)
|
||||
return response
|
||||
|
||||
def process_exception(self, request, exception):
|
||||
logger.exception(exception)
|
||||
return JsonResponse(
|
||||
{
|
||||
"success": False,
|
||||
"status_code": 500,
|
||||
"message": "Internal server error",
|
||||
"details": str(exception) # فقط در حالت توسعه! در تولید بهتر است لاگ شود.
|
||||
},
|
||||
status=500
|
||||
)
|
||||
Loading…
Add table
Reference in a new issue