def put(self, request, *args, **kwargs): #可以执行条件 #首先判断用户名是否 upk = kwargs['pk'] password = make_password(request.data['password']) aimdata = copy.deepcopy(request.data) print(aimdata) aimdata['password']=password print(aimdata) oldobj = User.objects.get(pk=upk) userserializer = UserSerializer(oldobj,data=aimdata,partial=True) if userserializer.is_valid(): userserializer.save() #如果创建成功,返回对应id的对应url returndata = { "desc":"user add", "data":{ "upk": upk }, "code":200, "error":0, "detail":"add success" } return Response(returndata,status=status.HTTP_200_OK)
def pre_save(self, obj): user_data = self.request.DATA.get('user', {}) thumbnail_image = self.request.DATA.get('thumbnail_image_obj', {}) main_image = self.request.DATA.get('main_image_obj', {}) full_name = user_data.get('full_name', '').split(' ') user_data['first_name'] = full_name[0] if thumbnail_image: obj.thumbnail_image.save( thumbnail_image['name'], ContentFile(thumbnail_image['file'].decode('base64')), save=False) if main_image: obj.main_image.save(main_image['name'], ContentFile( main_image['file'].decode('base64')), save=False) if len(full_name) > 1: user_data['last_name'] = ' '.join(full_name[1:]) user_serializer = UserSerializer(obj.user, data=user_data) if user_serializer.is_valid(): password = user_data.get('password_1', '') if password: if password == user_data.get('password_2', ''): user_serializer.object.set_password(password) user_serializer.save()
def put(self, request, pk, format=None): obj = User.objects.get(id=pk) serializer = UserSerializer(obj, data=request.data) if serializer.is_valid(): serializer.save() return update(serializer) return failure(serializer)
def patch(self, request, username): user = self.get_object(username) serializer = UserSerializer(user, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): data = request.data serializer = UserSerializer(data=data) if serializer.is_valid(raise_exception=True): serializer.save() return Response( 'Пользователь успешно зарегистрирован. Подтвердите аккаунт по почте', status=201)
def put(self, request, pk, format=None): try: user = get_object_or_404(User, pk) print(user) serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=200) except Http404 as e: message = {"message": "User does not exist"} return JsonResponse(message, status=404)
def post(self, request, format=None): serializer = UserSerializer(data=request.data) bucket = request.data['bucket'] tenants = User.objects.filter(bucket=bucket) if len(tenants) >= 5: message = {'message': 'Select another bucket'} return JsonResponse(message, status=400) if serializer.is_valid(): serializer.validated_data serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: return Response(serializer.data, status=status.HTTP_201_CREATED)
def put(self, request, pk, format=None): try: user = get_object_or_404(User, pk=pk) except Http404: message = {"message": "User does not exist"} return JsonResponse(message, status=404) serializer = UserSerializer(user, data=request.data) bucket = request.data['bucket'] tenants = User.objects.filter(bucket=bucket) if len(tenants) == 20: message = {'message': 'Select another bucket'} return JsonResponse(message, status=400) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=200) return JsonResponse(serializer.errors, status=400)
def get(self, request): hoy = datetime.date.today() agno = hoy.year """ Lista los datos del socio """ if request.method == 'GET': #En este caso se toman en cuenta a los socios vitalicios cuota = Account.objects.filter(cuota__fecha_fin__gte=str(agno) + '-12-31').distinct() socios = User.objects.filter(id__in=cuota).distinct() #socios = User.objects.all() serializer = UserSerializer(socios, many=True) return JSONResponse(serializer.data) elif request.method == 'POST': data = JSONParser().parse(request) serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.errors, status=400)
def api_detail_get_put_view(request): try: django_statsd.start('api.getUser.DB') account = Account.objects.get(email=request.user) django_statsd.stop('api.getUser.DB') except Account.DoesNotExist: logger.error("User Doesn't Exist") django_statsd.stop('api.getUser.DB') return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': django_statsd.incr('api.getUser') django_statsd.start('api.getUser.time.taken') serializer = UserSerializer(account) logger.info("GET: User with uuid: %s", account.uuid_id) django_statsd.stop('api.getUser.time.taken') return Response(serializer.data) elif request.method == 'PUT': django_statsd.incr('api.putUser') django_statsd.start('api.putUser.time.taken') serializer = UserSerializer2(account, data=request.data) data = {} if serializer.is_valid(): django_statsd.start('api.putUser.DB') serializer.save() django_statsd.stop('api.putUser.DB') data['response'] = 'successfully updated.' logger.info("PUT: User with uuid: %s", account.uuid_id) django_statsd.stop('api.putUser.time.taken') return Response(data=data, status=status.HTTP_204_NO_CONTENT) logger.error("ERROR: Something Happened: %s", serializer.errors) django_statsd.stop('api.putUser.time.taken') return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create_user_driver(self, request): email = request.data.get('email') username = request.data.get('username') pw1 = request.data.get('password') pw2 = request.data.get('password2') vehicle_id = request.data.get('vehicle_id') img = request.data.get('img') data = { 'email': email, 'username': username, 'password': pw1, 'password2': pw2 } serializer = UserSerializer(data=data) user_obj = None if serializer.is_valid(): user_obj = serializer.save() else: return Response({'res': 'user not valid'}, status=status.HTTP_400_BAD_REQUEST) deliverycompany_obj = request.user.deliverycompany driver_obj = Driver.objects.create( user=user_obj, delivery_company=deliverycompany_obj) if vehicle_id is not None: print(vehicle_id) vehicle_obj = Vehicle.objects.get(id=int(vehicle_id)) if hasattr(vehicle_obj, 'driver'): old_driver_obj = vehicle_obj.driver old_driver_obj.vehicle = None old_driver_obj.save() driver_obj.vehicle = vehicle_obj driver_obj.save() if img is not None: print('img is not None') driver_obj.image = img driver_obj.save() return Response({'driver_id': driver_obj.id}, status=status.HTTP_200_OK)
def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(raise_exception=True): user = serializer.save() if user: user = authenticate(email=request.data['email'].lower(), password=request.data['password']) if not user: print("I AM HERE") raise AuthFailed(detail=None, code=None) token = Token.objects.get_or_create(user=user) print(token) return Response( { "token": token[0].key, "email": user.email, "username": user.username }, status=status.HTTP_200_OK) # return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, *args, **kwargs): user_data = request.DATA.get('user', {}) thumbnail_image = self.request.DATA.get('thumbnail_image_obj', {}) main_image = self.request.DATA.get('main_image_obj', {}) full_name = user_data.get('full_name', '').split(' ') user_data['first_name'] = full_name[0] if len(full_name) > 1: user_data['last_name'] = ' '.join(full_name[1:]) pw1 = user_data.get('password_1', '1') pw2 = user_data.get('password_2', '2') if pw1 != pw2: error = {'password_1': ['Passwords do not match']} error['password_2'] = [''] return Response(error, status=status.HTTP_400_BAD_REQUEST) user_serializer = UserSerializer(data=user_data) profile_serializer = NewProfileSerializer(data=request.DATA) if user_serializer.is_valid() and profile_serializer.is_valid(): email = user_serializer.data.get('email', None) timezone = request.DATA.get('timezone', None) full_name = user_data.get('full_name', None) error = None if not email: error = {'email': ['This field is required.']} if not timezone: error = {'timezone': ['This field is required.']} if not full_name: error = {'full_name': ['This field is required.']} if error: return Response(error, status=status.HTTP_400_BAD_REQUEST) try: User.objects.get(email=email) error = {'email': ['User with given email already exists']} return Response(error, status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: #user_serializer.object.username = profile_serializer.object.user user_serializer.object.set_password(pw1) user_serializer.object.is_active = True user_serializer.save() if thumbnail_image: profile_serializer.object.thumbnail_image.save( thumbnail_image['name'], ContentFile(thumbnail_image['file'].decode('base64')), save=False) if main_image: profile_serializer.object.main_image.save( main_image['name'], ContentFile(main_image['file'].decode('base64')), save=False) profile_serializer.object.activationtoken = sha1( "%sxauto%s" % (randrange(1, 1000), randrange(1, 1000))).hexdigest() profile_serializer.object.user = user_serializer.object profile_serializer.save() #auth new user user = authenticate(email=user_serializer.object.email, password=pw1) auth_login(request, user) return Response(None, status=status.HTTP_201_CREATED) errors = user_serializer.errors errors.update(profile_serializer.errors) return Response(errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return success(serializer) return (serializer)
def post(self, request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED)