From c9331d490ad336f7c58576476c9c51bf57a075c5 Mon Sep 17 00:00:00 2001 From: mi1468 Date: Mon, 19 May 2025 17:26:54 +0330 Subject: [PATCH] set template to json response --- core/settings.py | 3 + core/urls.py | 1 + core/utils.py | 15 +++++ core/views/userView.py | 126 +++++++++++++++++++++++++++++------------ test.rest | 6 +- 5 files changed, 113 insertions(+), 38 deletions(-) create mode 100644 core/utils.py diff --git a/core/settings.py b/core/settings.py index ba10523..20f8175 100644 --- a/core/settings.py +++ b/core/settings.py @@ -50,6 +50,9 @@ INSTALLED_APPS = [ ] +REST_FRAMEWORK = { + 'EXCEPTION_HANDLER': 'core.utils.custom_exception_handler', +} MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', diff --git a/core/urls.py b/core/urls.py index 46e1bdf..c855aee 100644 --- a/core/urls.py +++ b/core/urls.py @@ -17,6 +17,7 @@ urlpatterns = [ re_path('signup', userView.signup , name="signup"), re_path('login', userView.login), + re_path('test_token', userView.test_token), re_path('editProfile/', userView.editProfile, name='edit-profile'), re_path('resetPassword/', userView.resetPassword, name='reset-password'), diff --git a/core/utils.py b/core/utils.py new file mode 100644 index 0000000..c5a1e7b --- /dev/null +++ b/core/utils.py @@ -0,0 +1,15 @@ +# in your_project/utils.py or a similar file + +from rest_framework.views import exception_handler + +def custom_exception_handler(exc, context): + response = exception_handler(exc, context) + + if response is not None: + response.data = { + "status": response.status_code, + "data": {}, + "message": str(exc.detail) if hasattr(exc, 'detail') else str(exc) + } + + return response diff --git a/core/views/userView.py b/core/views/userView.py index 9b73e29..c75a426 100644 --- a/core/views/userView.py +++ b/core/views/userView.py @@ -171,21 +171,51 @@ def sendCodeAndNewPassword(request): +# @api_view(['POST']) +# def login(request): +# try: +# customer = Customer.objects.get(mobile_number=request.data['mobile_number']) +# except get_user_model().DoesNotExist: +# return Response("User not found", status=status.HTTP_404_NOT_FOUND) + +# if not customer.user.check_password(request.data['password']): +# return Response("Invalid password", status=status.HTTP_401_UNAUTHORIZED) + +# token, created = Token.objects.get_or_create(user=customer.user) +# serializer = UserSerializer(customer.user) +# return Response({'token': token.key, 'user': serializer.data}) + + + @api_view(['POST']) def login(request): try: - customer = Customer.objects.get(mobile_number=request.data['mobile_number']) - except get_user_model().DoesNotExist: - return Response("User not found", status=status.HTTP_404_NOT_FOUND) + customer = Customer.objects.get(mobile_number=request.data['mobile_number']) + except Customer.DoesNotExist: + return Response({ + "status": 401, + "data": {}, + "message": "موبایل یا پسورد غلط است" + }, status=status.HTTP_401_UNAUTHORIZED) if not customer.user.check_password(request.data['password']): - return Response("Invalid password", status=status.HTTP_401_UNAUTHORIZED) + return Response({ + "status": 401, + "data": {}, + "message": "موبایل یا پسورد غلط است" + }, status=status.HTTP_401_UNAUTHORIZED) token, created = Token.objects.get_or_create(user=customer.user) serializer = UserSerializer(customer.user) - return Response({'token': token.key, 'user': serializer.data}) - + return Response({ + "status": 200, + "data": { + "token": token.key, + "user": serializer.data + }, + "message": "ورود با موفقیت انجام شد" + }, status=status.HTTP_200_OK) @@ -231,49 +261,47 @@ def sendSmsVerification(request): @authentication_classes([SessionAuthentication, TokenAuthentication]) @permission_classes([IsAuthenticated]) def getInfo(request): - # Retrieve the current user user = request.user - - # Assuming a OneToOneField relation between User and Customer + try: - # Retrieve the associated customer object customer = Customer.objects.get(user=user) - - # Get all images uploaded by this user + user_images = Image.objects.filter(user=user).order_by('-created_at') user_pdfs = Pdf.objects.filter(user=user).order_by('-created_at') user_videos = Video.objects.filter(user=user).order_by('-created_at') - user_glb = Glb.objects.filter(user=user).order_by('-created_at') + user_glbs = Glb.objects.filter(user=user).order_by('-created_at') + customer_serializer = CustomerSerializer(customer) image_serializer = ImageSerializer(user_images, many=True) pdf_serializer = PdfSerializer(user_pdfs, many=True) - Video_serializer = VideoSerializer(user_videos, many=True) - glb_serializer = GlbSerializer(user_glb, many=True) - - # Serialize the customer data - customer_serializer = CustomerSerializer(customer) - - # Manually select user fields to return + video_serializer = VideoSerializer(user_videos, many=True) + glb_serializer = GlbSerializer(user_glbs, many=True) + user_data = { 'id': user.id, 'first_name': user.first_name, 'last_name': user.last_name, - # add any other fields you need } - + return Response({ - 'customer': customer_serializer.data, - 'user': user_data, - 'images': image_serializer.data , # Add images to response - 'pdfs': pdf_serializer.data , # Add images to response - 'videos': Video_serializer.data ,# Add images to response - 'glbs': glb_serializer.data , # Add images to response - }) - + 'status': 200, + 'data': { + 'customer': customer_serializer.data, + 'user': user_data, + 'images': image_serializer.data, + 'pdfs': pdf_serializer.data, + 'videos': video_serializer.data, + 'glbs': glb_serializer.data, + }, + 'message': 'موفق' + }, status=status.HTTP_200_OK) + except Customer.DoesNotExist: - # If no customer object exists for the user, return an error response - return Response({'error': 'No customer data found for this user'}, status=404) - + return Response({ + 'status': 404, + 'data': {}, + 'message': 'اطلاعات مشتری یافت نشد' + }, status=status.HTTP_404_NOT_FOUND) @@ -395,14 +423,42 @@ def submitSmsVerification(request): +# @api_view(['GET']) +# @authentication_classes([SessionAuthentication, TokenAuthentication]) +# @permission_classes([IsAuthenticated]) +# def test_token(request): +# if not user_has_role(request.user, 'admin'): +# return Response({'message': 'No access'}, status=status.HTTP_403_FORBIDDEN) + +# return Response({'message': 'User has admin role'}) + + + + + + + @api_view(['GET']) @authentication_classes([SessionAuthentication, TokenAuthentication]) @permission_classes([IsAuthenticated]) def test_token(request): if not user_has_role(request.user, 'admin'): - return Response({'message': 'No access'}, status=status.HTTP_403_FORBIDDEN) + return Response({ + "status": 403, + "data": {}, + "message": "دسترسی غیرمجاز" + }, status=status.HTTP_403_FORBIDDEN) + + return Response({ + "status": 200, + "data": { + "username": request.user.username + }, + "message": "موفق" + }, status=status.HTTP_200_OK) + + - return Response({'message': 'User has admin role'}) diff --git a/test.rest b/test.rest index 107316a..1daaa14 100644 --- a/test.rest +++ b/test.rest @@ -10,7 +10,7 @@ Content-Type: application/json POST http://127.0.0.1:8000/login Content-Type: application/json -{ "mobile_number":"09140086509", "password": "123456" } +{ "mobile_number":"09140086509", "password": "12345678" } ### @@ -30,7 +30,7 @@ Authorization: token d3f1b03996140c8f7561d67221953ff704b482cb GET http://127.0.0.1:8000/test_token Content-Type: application/json -Authorization: token c362581117e209735d412226e54596867e370892 +Authorization: token 224648840820ad0948ddee5b00d53ae67c040c49 # Authorization: token 53e2b003a92e22aca85c95088a438ece8d9a5dfb @@ -38,7 +38,7 @@ Authorization: token c362581117e209735d412226e54596867e370892 GET http://127.0.0.1:8000/getInfo Content-Type: application/json -Authorization: token 3d5ab31449b6a075e3967559526d5e31977431a1 +Authorization: token 224648840820ad0948ddee5b00d53ae67c040c49 # Authorization: token 53e2b003a92e22aca85c95088a438ece8d9a5dfb