def put(self, request, pk, *args, **kwargs): try: user = self.get_object(pk) user_serializer = ProfileSerializer(instance=user, data=request.data) if user_serializer.is_valid(): user = user_serializer.save() return Response(user_serializer.data, status=status.HTTP_200_OK) else: message = '' for error in user_serializer.errors.values(): message += " " message += error[0] return Response({ 'status': False, 'message': message }, status=status.HTTP_400_BAD_REQUEST) except Exception as e: return Response({ 'status': False, 'message': str(e) }, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None): serializer = ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk, format=None): user = get_object_or_404(Profile, pk=pk) serializer = ProfileSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): """ Creates Profile record """ serializer = ProfileSerializer(data=request.data) if serializer.is_valid(raise_exception=ValueError): serializer.create(validated_data=request.data) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST)
class InstantDeliveryOrderSerializer(serializers.ModelSerializer): buyer = ProfileSerializer(read_only=True) courier = ProfileSerializer(read_only=True) feedback = serializers.ReadOnlyField() priceRange = serializers.DecimalField(max_digits=5, decimal_places=2) class Meta: model = InstantDeliveryOrder fields = '__all__' def create(self, validated_data): order = InstantDeliveryOrder.objects.create(**validated_data) order.buyer = validated_data['buyer'] order.save() return order
def my_jwt_response_handler(token, user=None, request=None): return { 'token': token, 'user': ProfileSerializer(user, context={ 'request': request }).data }
def get(self, format=None): """ Get all the profile records """ profiles = Profile.objects.all() serializer = ProfileSerializer(profiles, many=True) return Response(serializer.data)
def verifySignup(request): activation_key = request.data.get("activationKey") profile = get_object_or_404(Profile, activationKey=activation_key) profile.accountTier = AccountTier.TIER_1 profile.save() profileSerializer = ProfileSerializer(profile) return Response({ 'success': True, 'profile': profileSerializer.data, })
def test_retreive_profile(self): """Test retreiving a profile""" sample_profile(user=self.user) res = self.client.get(PROFILE_URL) profile = Profile.objects.all().order_by('-id') serializer = ProfileSerializer(profile, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data[0], serializer.data[0])
class InstantDeliveryCourierSerializer(serializers.ModelSerializer): profile = ProfileSerializer(read_only=True) class Meta: model = InstantDeliveryCourier fields = '__all__' def create(self, validated_data): courier = InstantDeliveryCourier.objects.create(**validated_data) courier.profile = validated_data['profile'] courier.save() return courier
def enable2FAGoogle(request): user = request.user try: profile = Profile.objects.get(user=user) profile.enable2FAGoogle = request.data.get("enable2FAGoogle") if profile.enable2FAGoogle: profile.enable2FASMS = False profile.save() profileSerializer = ProfileSerializer(profile, context={'request': request}) return Response({'success': True, 'profile': profileSerializer.data}) except Profile.DoesNotExist: return Response({'success': False, 'error': 'profile.notfound'})
def deleteAddress(request, address_id): try: user = request.user profile = Profile.objects.get(user=user) address = Address.objects.get(id=address_id) profile.addresses.remove(address) profile.save() address.delete() profileSerializer = ProfileSerializer(profile, context={'request': request}) return Response({'success': True, 'profile': profileSerializer.data}) except Exception as e: return Response({'success': False, 'error': e.message})
def editAddress(request): user = request.user try: profile = Profile.objects.get(user=user) address = Address.objects.get(id=request.data.get("id")) addressSerializer = AddressSerializer(data=request.data) if addressSerializer.is_valid(): address = addressSerializer.update(address, request.data) address.save() profileSerializer = ProfileSerializer(profile, context={'request': request}) return Response({'success': True, 'profile': profileSerializer.data}) except Profile.DoesNotExist: return Response({'success': False, 'error': 'profile.notfound'})
def get(self, request, format=None): posts = Post.objects.all() data = [] for user in Profile.objects.all(): posts = Post.objects.filter(user=user) serializer_posts = PostSerializer(posts, many=True) serializer_user = ProfileSerializer(user) data.append({ 'user': serializer_user.data, 'posts': serializer_posts.data }) return Response(data=data, status=status.HTTP_200_OK)
def addAddress(request): user = request.user try: profile = Profile.objects.get(user=user) addressSerializer = AddressSerializer(data=request.data) address = addressSerializer.create(request.data) address.save() profile.addresses.add(address) profile.save() profileSerializer = ProfileSerializer(profile, context={'request': request}) return Response({'success': True, 'profile': profileSerializer.data}) except Profile.DoesNotExist: return Response({'success': False, 'error': 'profile.notfound'})
def login(request): username = request.data.get("username") if username: username = username.lower() password = request.data.get("password") disableLogEvent = request.data.get("disableLogEvent") user = authenticate(username=username, password=password) if not user: #maybe email try: user2Try = User.objects.get(email__iexact=username) user = authenticate(username=user2Try.username, password=password) except Exception as ex: user2Try = None user = None if not user2Try: return Response({ "success": False, "error": "login.failed" }, status=HTTP_401_UNAUTHORIZED) try: profile = Profile.objects.get(user=user) if not profile.mobileVerified: return Response({ "success": False, "error": 'mobile.notverified', 'activationKey': profile.activationKey }) wallet = Wallet.objects.get(profile=profile) profileSerializer = ProfileSerializer(profile, context={'request': request}) except Profile.DoesNotExist: return Response({ "success": False, "error": "login.failed" }, status=HTTP_401_UNAUTHORIZED) token, _ = Token.objects.get_or_create(user=user) if not disableLogEvent: Event().createEvent('LOGIN', 'USERACTIVITY', '', profile, request) return Response({ "success": True, "token": token.key, 'profile': profileSerializer.data, })
def uploadUserAvatar(request): user = request.user profile = Profile.objects.get(user=user) file = request.data.get('avatarImage') if file: if type(file) is dict: file = file['changingThisBreaksApplicationSecurity'] if file.find("http://") > -1 or file.find("https://") > -1: imgstr = base64.b64encode(requests.get(file).content) ext = file.split('/')[-1].split(".")[-1] avatarImageName = "%d.%s" % (user.id, ext) data = ContentFile(base64.b64decode(imgstr), name=avatarImageName) if data.size > settings.MAX_IMAGE_SIZE_UPLOAD: return Response({ 'success': False, 'error': 'file.toobig' }, 500) if profile.avatarImage: profile.avatarImage.delete(save=True) profile.avatarImage = data profile.save() return Response({'success': True}) else: datapost = request.data.get('avatarImage') if type(datapost) is dict: datapost = datapost['changingThisBreaksApplicationSecurity'] format, imgstr = datapost.split(';base64,') ext = format.split('/')[-1] avatarImageName = "%d.%s" % (user.id, ext) data = ContentFile(base64.b64decode(imgstr), name=avatarImageName) if data.size > settings.MAX_IMAGE_SIZE_UPLOAD: return Response({ 'success': False, 'error': 'file.toobig' }, 500) if profile.avatarImage: profile.avatarImage.delete(save=True) profile.avatarImage = data profile.save() profileSerializer = ProfileSerializer(profile, context={'request': request}) return Response({ 'success': True, 'profile': profileSerializer.data }) return Response({'success': False})
def userProfile(request): user = request.user try: profile = Profile.objects.get(user=user) wallet = Wallet.objects.get(profile=profile) profileSerializer = ProfileSerializer(profile, context={'request': request}) walletSerializer = WalletSerializer(wallet, context={'request': request}) return Response({ 'success': True, 'profile': profileSerializer.data, 'wallet': walletSerializer.data }) except Exception as e: return Response({'success': False, 'error': e.message})
def test_profile_limited_to_user(self): """Test retrieving profile for user""" user2 = get_user_model().objects.create_user( email='*****@*****.**', password='******', username='******' ) sample_profile(user=user2) sample_profile(user=self.user) res = self.client.get(PROFILE_URL) profiles = Profile.objects.filter(user=self.user) serializer = ProfileSerializer(profiles, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data[0], serializer.data[0])
def updateProfileSetting(request): user = request.user settingName = request.data.get('settingName') settingValue = request.data.get('settingValue') try: profile = Profile.objects.get(user=user) if hasattr(profile, settingName): profile.__setattr__(settingName, settingValue) profile.save() profileSerializer = ProfileSerializer(profile, context={'request': request}) return Response({ 'success': True, 'profile': profileSerializer.data }) return Response({ 'success': False, 'error': "no field with name %s" % settingName }) except Exception as e: return Response({'success': False, 'error': e.message})
def get(self, request, format=None): """ Return UUID and sessions array for a user. UUID can be used to display public profile. """ user = request.user response_obj = {} try: data = get_object_or_404(PersonSession, user=user) personSessionSerialized = PersonSessionSerializer(data) response_obj['sessions'] = personSessionSerialized.data['sessions'] except Http404: response_obj['sessions'] = [] profile = Profile.objects.filter(user=user).first() profileSerialized = ProfileSerializer(profile) response_obj['uuid'] = profileSerialized.data['id'] return Response(response_obj)
def get(self, request, pk, format=None): user = self.get_object(pk) serializer = ProfileSerializer(user) return Response(serializer.data)
def get(self, request, pk, format=None): user = get_object_or_404(Profile, pk=pk) serializer = ProfileSerializer(user) return Response(data=serializer.data, status=status.HTTP_200_OK)
def get(self, request, format=None): profiles = Profile.objects.all() serializer = ProfileSerializer(profiles, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK)