def post(self, request): data = request.data serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(serializer.errors, status=400)
def put(self, request, pk, format=None): user = self.get_object(pk) serializer = UserSerializer(user, data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def add_user_to_database(data): serializer = UserPaymentSerializer(data=data) if serializer.is_valid(): user = serializer.save() if user: user_data = {} user_phone = data.get('sender_phone') user_phone = format_phone_number(user_phone) user_password = "******" user_data['phone_number'] = user_phone user_data['balance'] = data.get('amount') user_data['password'] = user_password jibambe_user_serializer = UserSerializer(data=user_data) if jibambe_user_serializer.is_valid(): jibambe_user_serializer.save() response = {"status": "01", "description": "Accepted", "subscriber_message": "Welcome to Jibambe na Ma Movie. Your account details are " \ "Phone:{0} Password: {1}".format(user_phone, user_password)} return response, status.HTTP_200_OK else: return jibambe_user_serializer.errors, status.HTTP_400_BAD_REQUEST return serializer.errors, status.HTTP_400_BAD_REQUEST
def userDetailApi(request, *args, **kwargs): if request.method == 'GET': nim = kwargs['pk'] user = CustomUser.objects.filter(nim=nim) if user: serializer = UserSerializer(user[0]) return Response({ 'count': 1, 'results': [ {**serializer.data} ] }) else: return Response({ 'count': 0, 'results': [] }) if request.method == 'PUT': nim = kwargs['pk'] user = get_object_or_404(CustomUser, nim=nim) serializer = UpdateUserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response( serializer.data, ) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) if request.method == 'DELETE': nim = kwargs['pk'] user = get_object_or_404(CustomUser, nim=nim) user.delete() return Response(status=status.HTTP_200_OK)
def create_user(request): """ { "email": "*****@*****.**", "password": "******", "gender": "m", "type": "i" } """ data = request.data data['emoji'], data['nickname'] = get_nickname() serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response( { "status": "success", "message": "회원가입에 성공하였습니다.", "data": { "nickname": data['nickname'], "emoji": data['emoji'] } }, status=status.HTTP_201_CREATED) return Response({ "status": "fail", "message": serializer.errors }, status=status.HTTP_400_BAD_REQUEST)
def update_user_keyword(request): user = request.user keyword1_list = Rating.objects.filter(user_id=user.id).values('keyword1').annotate(key_cnt=Count('keyword1')).order_by('-key_cnt') keyword2_list = Rating.objects.filter(user_id=user.id).values('keyword2').annotate(key_cnt=Count('keyword2')).order_by('-key_cnt') key_cnts = {} for keyword in keyword1_list: if keyword.get('keyword1') in key_cnts.keys(): key_cnts[keyword['keyword1']] += keyword['key_cnt'] else: key_cnts[keyword['keyword1']] = keyword['key_cnt'] for keyword in keyword2_list: if keyword.get('keyword2') in key_cnts.keys(): key_cnts[keyword['keyword2']] += keyword['key_cnt'] else: key_cnts[keyword['keyword2']] = keyword['key_cnt'] import collections sorted_cnts = sorted(key_cnts.items(), key=lambda kv: kv[1], reverse=True) sorted_key_cnts = collections.OrderedDict(sorted_cnts) sorted_key_cnts_keylist = list(sorted_key_cnts) keyword1 = sorted_key_cnts_keylist[0] keyword2 = sorted_key_cnts_keylist[1] serializer = UserSerializer(instance=user, data={'keyword1':keyword1, 'keyword2':keyword2}, partial=True) if serializer.is_valid(): serializer.save() return Response(status=200, data={'message': '평점 작성 성공'})
def user_detail(request, pk): """ Retrieve, update or delete a code snippet. """ if request.user.is_authenticated: try: user = User.objects.get(pk=pk) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = UserSerializer(user) return Response(serializer.data) elif request.method == 'PUT': request.data['password'] = hashlib.sha256( str(request.data['password']).encode()).hexdigest() serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': user.delete() return Response({'mgs': "success"}, status=status.HTTP_204_NO_CONTENT) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'msg': "login required"}, status=status.HTTP_403_FORBIDDEN)
def put(self, request, *args, **kwargs): serializer = UserSerializer(request.user, data=request.data) # user = self.get_object(pk) # serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, 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 test_update_preferred_valid_name(self): data = {"first_name": "new_preferred"} serializer = UserSerializer(self.user, data=data, partial=True) self.assertTrue(serializer.is_valid()) serializer.save() self.assertEqual(self.user.preferred_name, "new_preferred") self.assertEqual(self.user.first_name, "First")
def create(self, request, *args, **kwargs): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() tasks.message.delay('verify', recipient=request.data['email']) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create_user(request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({'message': Message.SUCCESS}, status=status.HTTP_201_CREATED) else: return Response({'message': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
def test_preferred_same_as_first(self): data = {"first_name": "First2"} serializer = UserSerializer(self.user_preferred_name, data=data, partial=True) self.assertTrue(serializer.is_valid()) serializer.save() self.assertEqual(self.user_preferred_name.preferred_name, "") self.assertEqual(self.user_preferred_name.first_name, "First2")
def patch(request): user = request.user serializer = UserSerializer(user, data=request.data, context={'request': request}, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) # return JsonResponse(user, safe=False) 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(): # user validation success serializer.save() data = {"message": "User got Registered successfully"} return Response(data=data) else: # user validation failed status_code = status.HTTP_400_BAD_REQUEST return Response(serializer.errors, status=status_code)
def post(self, request, format=None): user_client_serializer = UserSerializer(data=request.data) #print(serializer) if user_client_serializer.is_valid(): user_client_serializer.save() # user = user_client_serializer.create # print(user) data_dict = { "status": 201, "data": user_client_serializer.data, 'id': user_client_serializer.data['id'] } return Response(data_dict, status=status.HTTP_201_CREATED) return Response(user_client_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: return Response(status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def signup(request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() auth_login(request, user) return Response(UserSerializer(instance=user).data, status=status.HTTP_201_CREATED)
def post(self, request): data = request.data response_data = {} response_data["success"] = True if not 'email' in data: response_data["message"] = _("email is required ") response_data["success"] = False return Response(data=response_data, status=status.HTTP_400_BAD_REQUEST) existUser = self.getObjectOrNone(User, email=data["email"]) if existUser is not None: response_data["success"] = False response_data["message"] = _("Email already in use") return Response(data=response_data, status=status.HTTP_206_PARTIAL_CONTENT) serializer = UserSerializer(data=data, many=False) if not serializer.is_valid(): response_data["success"] = False response_data["message"] = self.returnSerializerErrors(serializer.errors) return Response(data=response_data, status=status.HTTP_400_BAD_REQUEST) created_user = serializer.save() response_data = ProfileSerializer(created_user, many=False).data return Response(data=response_data, status=status.HTTP_201_CREATED)
def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() user.roles.add(Role.USER) user.save() to_email = serializer.data.get('email') from_email = settings.EMAIL_HOST_USER token = RefreshToken.for_user(user).access_token domain_name = get_current_site(request).domain relativeLink = reverse('email-verify') final_link = "http://localhost:3000/activate/" + str(token) subject = 'Activate your account' message = 'Hi, ' + user.first_name + ' ' + user.last_name + ' click on this link to activate your account.\n' + final_link send_mail(subject, message, from_email, [ to_email, ]) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() return Response(serializer.data) else: return Response(serializer.errors)
def update(self, request, pk): """ Actualiza el usuario con pk <pk> si existe. :param request: objeto de tipo HttpRequest :param pk: pk del usuario que queremos actualizar :return: 202 si OK o 400 con errores """ user = get_object_or_404(User, pk=pk) self.check_object_permissions(request, user) serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_202_ACCEPTED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, request): serializer = UserSerializer( data={ "username": request.data.get("username"), "password": request.data.get("password"), "first_name": request.data.get("firstName"), "last_name": request.data.get("lastName"), "email": request.data.get("email"), }) serializer.is_valid(raise_exception=True) new_user = serializer.save() sponsee_serializer = SponseeCreateSerializer( data={ "user": new_user.pk, "address": request.data.get("address"), "phone": request.data.get("phone"), "birth_certificate": request.data.get("birthCertificate"), "national_id": request.data.get("nationalId"), }) sponsee_serializer.is_valid(raise_exception=True) new_sponsee = sponsee_serializer.save() headers = self.get_success_headers( SponseeCreateSerializer(new_sponsee).data) return Response(SponseeListSerializer(new_sponsee).data, headers=headers)
def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() user.set_password(request.data['password']) user.save() return Response(serializer.data, status=201) return Response(serializer.errors, status=400)
def user_register(request, format=None): """ register an account with username and password parameters """ username = request.query_params.get('username', None) password = request.query_params.get('password', None) user = Users(Username=username, Password=password) serializer = UserSerializer(user) serializer = UserSerializer(data=serializer.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def userListApi(request): if request.method == 'GET': pagination_class = api_settings.DEFAULT_PAGINATION_CLASS paginator = pagination_class() queryset = CustomUser.objects.filter(is_staff=False).order_by('nim') page = paginator.paginate_queryset(queryset, request) serializer = UserSerializer(page, many=True) return paginator.get_paginated_response(serializer.data) if request.method == 'POST': data = request.data serializer = RegisterSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def register(request, format='json'): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: api_key, key = APIKey.objects.create_key(name="remote-access-key") Token.objects.get_or_create(user=user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create_user(request): if request.method == 'POST': serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format='json'): serializer = UserSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): user = serializer.save() if user: json = serializer.data return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format='json'): serializer = UserSerializer(data=request.data) print('post -> data', request.data) if serializer.is_valid(): user = serializer.save() if user: return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): logger.info("UpdatePasswordView.post is called. User: {0}".format(request.user.log_guid)) # TODO: check if front end sends a json file or normal request data = request.data update_password_serializer = self.serializer_class(data=data) if update_password_serializer.is_valid(): password = update_password_serializer.validated_data['password'] account = authenticate(email=request.user.email, password=password) if account is not None: if account.is_active: new_password = update_password_serializer.validated_data['new_password'] try: # we use partial to avoid passing required fields into serializer serializer = UserSerializer(account, data={'password': new_password}, partial=True) if serializer.is_valid(): serializer.save() account = authenticate(email=request.user.email, password=new_password) login(request, account) logger.info(self.msgs['finish_success'].format(request.user.log_guid)) return Response({ 'status': _('Success'), 'message': self.msgs['update_pass_success']}, status=status.HTTP_200_OK) else: logger.error(self.errs['ser_not_valid'].format(data)) return Response({'status': _('Bad request'), 'message': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: logger.exception(self.errs['exception'].format(e.message)) return Response({'status': _('Bad request'), 'message': self.msgs['internal_server_error']}, status=status.HTTP_400_BAD_REQUEST) else: logger.error(self.errs['user_inactive'].format(request.user.log_guid)) return Response({'status': _('Unauthorized'), 'message': self.msgs['cannot_update_pass']}, status=status.HTTP_401_UNAUTHORIZED) else: logger.error(self.errs['combination_invalid']) return Response({ 'status': _('Unauthorized'), 'message': self.msgs['combination_invalid']}, status=status.HTTP_401_UNAUTHORIZED) else: logger.error(update_password_serializer.errors) return Response({'status': 'Bad request', 'message': self.msgs['password_mismatch'], 'errors': 'Validation error'}, status=status.HTTP_400_BAD_REQUEST)
def sign_up(request, format='json'): """ Creates the user. """ serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format='json'): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: token = Token.objects.create(user=user) json = serializer.data json['token'] = token.key return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def setUp(self): self.url = reverse('auth') # User info self.username = '******' self.email = '*****@*****.**' self.password = '******' # make sure our example data is valid serializer = UserSerializer(data={'username': self.username, 'email': self.email, 'password': self.password}) if serializer.is_valid(): self.user = serializer.save() else: self.fail()
def setUp(self): # url self.user_list = 'api:user-list' self.user_detail = 'api:user-detail' # User info self.username = '******' self.email = '*****@*****.**' self.password = '******' # make sure our example data is valid serializer = UserSerializer(data={'username': self.username, 'email': self.email, 'password': self.password}) if serializer.is_valid(): self.user = serializer.save() else: self.fail()
def post(self, request, format='json'): serializer = UserSerializer(data=request.data) if serializer.is_valid(): #print("Valid") user = serializer.save() if user: if request.data["isStudent"] == 1: new_student = Student(user=user, contact_no=request.data["contact_no"]) new_student.save() elif request.data["isStudent"] == 0: new_teacher = Teacher(user=user, contact_no=request.data["contact_no"]) new_teacher.save() else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) token = Token.objects.create(user=user) json = serializer.data json['token'] = token.key return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def setUp(self): self.token_list = 'api:token-list' self.token_detail = 'api:token-detail' # Clients cannot be created via view or serialzier self.name = 'reddit' self.api_url = 'https://oauth.reddit.com/api/v1/' self.authorize_url = 'https://www.reddit.com/api/v1/' self.token_url = 'https://www.reddit.com/api/v1/access_token/' self.client_id = 'some-client-id' self.client_secret = 'some-secret' self.redirect_uri = 'http://*****:*****@example.com' self.password = '******' # make sure our example data is valid serializer = UserSerializer(data={'username': self.username, 'email': self.email, 'password': self.password}) if serializer.is_valid(): self.user = serializer.save() else: self.fail()
def post(self, request): data = json.loads(request.body) guid = data.get('guid', None) logger.info("SetPasswordView.post is called. GUID: {0}".format(guid)) password_serializer = PasswordSerializer(data=data, partial=True) if not password_serializer.is_valid(): return Response({ 'status': _('Bad request'), 'message': self.msgs['password_mismatch'], 'errors': 'Validation error' }, status=status.HTTP_400_BAD_REQUEST) try: user_uid = UserUID.objects.get(guid=guid) except ObjectDoesNotExist: logger.exception(self.errs['GUID_invalid'].format(guid)) return Response({ 'status': _('Bad request'), 'message': self.msgs['activation_invalid'] }, status=status.HTTP_400_BAD_REQUEST) now_offset_aware = timezone.make_aware(datetime.datetime.utcnow(), timezone.get_current_timezone()) if user_uid.expiration_date < now_offset_aware: logger.error(self.errs['GUID_expired'].format(guid, user_uid.expiration_date, now_offset_aware)) return Response({ 'status': _('Bad request'), 'message': self.msgs['activation_invalid'] }, status=status.HTTP_400_BAD_REQUEST) try: account = User.objects.get(id=user_uid.user_id) except ObjectDoesNotExist: logger.exception(self.msgs['GUID_invalid'].format(guid)) return Response({ 'status': _('Fail'), 'message': self.msgs['internal_server_error'] }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) if account is not None: se_data = dict() se_data['password'] = password_serializer.validated_data['new_password'] se_data['confirm_password'] = password_serializer.validated_data['confirm_password'] se_data['email'] = account.email se_data['username'] = account.username se_data['log_guid'] = account.log_guid try: with transaction.atomic(): serializer = UserSerializer(account, data=se_data) if serializer.is_valid(): serializer.save() # We need to mark the forgotpassword GUID as expired uid_data = dict() uid_data['guid'] = guid uid_data['user'] = user_uid.user_id uid_data['expiration_date'] = datetime.datetime.utcnow() uidSerializer = UserUIDSerializer(user_uid, data=uid_data) if uidSerializer.is_valid(): uidSerializer.save() logger.info(self.msgs['finish_success'].format(guid)) return Response({ 'status': _('Success'), 'message': self.msgs['update_pass_success'] }, status=status.HTTP_200_OK) else: logger.error(self.errs['ser_not_valid'].format(guid, user_uid.user_id, uid_data['expiration_date'])) return Response({ 'status': _('Fail'), 'message': self.msgs['internal_server_error'] }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: logger.error(self.errs['server_error']) return Response({ 'status': _('Fail'), 'message': self.msgs['internal_server_error'] }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) except Exception as e: logger.exception(self.errs['exception'].format(guid, e.message)) return Response({ 'status': _('Bad request'), 'message': self.msgs['internal_server_error'] }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: logger.exception(self.errs['GUID_none'].format(guid)) return Response({ 'status': _('Bad request'), 'message': self.msgs['activation_invalid'] }, status=status.HTTP_400_BAD_REQUEST)