def post(self, request): try: username = bleach.clean(request.data.get('username')) password = bleach.clean(request.data.get('password')) firstname = bleach.clean(request.data.get('firstname')) lastname = bleach.clean(request.data.get('lastname')) email = bleach.clean(request.data.get('email')) location = bleach.clean(request.data.get('location')) #GetCoordinates returns the coordinates based on the users input location - provided by gooogle api coordinates = getCoordinates(location) user = User.objects.create_user(username=username, password=password) user.save() profile = Profile(user=user, FirstName=firstname, LastName=lastname, EmailAddress=email, Location=location, coordinates=coordinates) profile.save() serializer = ProfileSerializer(profile) return Response({ 'user': serializer.data, "token": AuthToken.objects.create(user) }) except: return HttpResponseBadRequest()
def profiles(request): if request.method == 'GET': user = request.GET.get('user', request.GET.get('user', None)) title = request.GET.get('title', None) profiles = Profile.objects.all() serializer = ProfileSerializer(profiles, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) if request.method == 'DELETE': Profile.objects.all() profile.delete() return Response(status=status.HTTP_200_OK) if request.method == 'POST': profiles = request.data.get('profiles', None) for profile in profiles: user = profile.get('user', None) gender = profile.get('gender', None) age = profile.get('age', None) occupation = profile.get('occupation', None) if not (user and gender and age): continue Profile(user=user, gender=gender, age=age, occupation=occupation).save() return Response(status=status.HTTP_200_OK)
def create(self, validated_data): user = User(**validated_data) user.set_password(validated_data['password']) user.save() profile = Profile(user=user) profile.save() return user
def register(request): username = request.POST.get('username') password = request.POST.get('password') email = request.POST.get('email') phone_number = request.POST.get('phone_number') city = request.POST.get('city') type_account = request.POST.get('type_account') try: user = User(username = username, password=password, email=email) user.set_password(password) user.save() print('----> save user') # create token token = jwt.encode({'some': username}, 'secret', algorithm='HS256') print(token) account = Profile(user=user, phone=phone_number, city=city, token=token, type_account = type_account, updated_by = user, created_by=user) account.save() print('-------> save account') # timezone.now() response = { 'result' : user.id } except: response = { 'result' : -999 } return JsonResponse(response)
def profile(self,user): profile = Profile( user = user ) profile.save() profile.countries.set(self.countries.all()) return profile
def post(self, request, *args, **kwargs): """ Create a new user and a basic profile for the user. Return the user profile id and user data. :param request: :param args: :param kwargs: :return: """ user_serializer = UserSerializer(data=request.data) # If the data isn't valid we return the error messages if not user_serializer.is_valid(): return Response(user_serializer.errors, status=400) # Otherwise we save the user and create a profile for the user user_serializer.save() user_profile = Profile( user=user_serializer.instance ) user_profile.save() ret = user_serializer.to_representation(user_serializer.instance) ret['profile_id'] = user_profile.id return Response(ret, status=201)
def create_profile(self, my_user, my_first_name, my_last_name, my_email, my_location, my_coords): return Profile(user=my_user, FirstName=my_first_name, LastName=my_last_name, EmailAddress=my_email, Location=my_location, coordinates=my_coords)
def register_user(request): """Use this method to register user.""" register_data = decode_json(request) user = User.objects.create_user(**register_data) user.save() profile = Profile(user=user, is_investor=False) profile.save() return JsonResponse(StatusCode.SUCCESS)
def create_token(): email = request.json.get("email", None) password = request.json.get("password", None) if email is None: return jsonify({"msg": "No email was provided"}), 400 if password is None: return jsonify({"msg": "No password was provided"}), 400 user = User.query.filter_by(email=email, password=password).first() if user is None: # the user was not found on the database return jsonify({"msg": "Invalid username or password"}), 401 else: todos = Todolist.query.filter_by(user_id=user.id).first() favs = Favorites.query.filter_by(user_id=user.id).first() profile = Profile.query.filter_by(user_id=user.id).first() if todos is None: new_todolist = Todolist() new_todolist.tasks = [""] new_todolist.user_id = user.id db.session.add(new_todolist) db.session.commit() print(new_todolist) else: pass if favs is None: new_favs = Favorites() new_favs.favs = [""] new_favs.user_id = user.id db.session.add(new_favs) db.session.commit() else: pass if profile is None: new_profile = Profile() new_profile.user_id = user.id new_profile.user_image = [""] new_profile.personal_description = [""] new_profile.occupation = [""] new_profile.location = [""] new_profile.hobbies = [""] db.session.add(new_profile) db.session.commit() else: pass print(user) # create a new token with the user id inside access_token = create_access_token(identity=user.id) return jsonify({"token": access_token, "user_id": user.id}), 200
def post(self, request, format=None): access_key_check(request) country_code = request.data['country_code'] number = request.data['number'] first_name = request.data['first_name'] last_name = request.data['last_name'] email = request.data['email'] if 'photo' in request.FILES: photo = request.data['photo'] else: photo = '' udid = request.data['udid'] phone = Phone.objects.get( Q(country_code=country_code) & Q(number=number)) sms_code_udid = SmsCode.objects.get(phone=phone).udid if udid == '': raise AccessDenied("Нет udid") if udid != sms_code_udid: raise AccessDenied("udids не совпадают") if Profile.objects.filter(phone=phone).count() > 0: raise ProfileEngaged( "Аккаунт с указанным номером телефона уже существует") profile = Profile() profile.phone = phone profile.first_name = first_name profile.last_name = last_name profile.email = email if photo: profile.photo = upload_photo(photo, phone) else: profile.photo = '' host = request.META['HTTP_HOST'] if host.startswith('www.'): host = host[4:] profile.payment_url = host + "/" + str(profile.external_id) try: qr = requests.get('https://api.scanova.io/v2/qrcode/url' + '?url=' + profile.payment_url + '&apikey=' + settings.SCANOVA_API_KEY) profile.qr = upload_qr(qr.content, phone) except: profile.qr = '' profile.save() token = Token.objects.create(profile=profile) result = {'token': token.token} return Response(result, status=status.HTTP_201_CREATED)
def post(self, request): code = request.data["code"] CLIENT_ID = settings.SPOTIFY_CLIENT_ID CLIENT_SECRET = settings.SPOTIFY_CLIENT_SECRET REDIRECT_URI = settings.REDIRECT_URI auth_info = spotify_wrapper.exchange_code(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, code) access_token = auth_info["access_token"] spotify = tk.Spotify(access_token) user_info = spotify.current_user() user_id = user_info.id user_email = user_info.email user = User.objects.filter(username=user_id) # If this is a new user, create an entry for them if len(user) == 0: new_user = User.objects.create_user( user_id, user_email, "", first_name=user_info.display_name) new_user.set_unusable_password() new_user.save() new_user_profile = Profile(user=new_user) new_user_profile.save() new_user_data = SpotifyApiData( user=new_user, access_token=auth_info["access_token"], refresh_token=auth_info["refresh_token"], access_expires_at=timezone.now() + datetime.timedelta(seconds=auth_info["expires_in"]), ) new_user_data.save() new_user_options = PlaylistOptions(user=new_user) new_user_options.save() user = new_user else: user = user[0] refresh = RefreshToken.for_user(user) return Response({ "refresh": str(refresh), "access": str(refresh.access_token), })
def apiProfile(request): print request.body error = 'bad Json: ' try: if request.method == 'GET': answer = toJson(Profile.objects.all()) return HttpResponse(answer) data = request.body data = json.loads(data) if request.method == 'POST': query = data['query'] email = data['email'] try: if query == 'select': p = Profile.objects.filter(email=email) return HttpResponse(toJson(p)) except: error = 'Profile ' + email + ' dose not exist.' if request.method == 'PUT': try: email = data['email'] surname = data['surname'] name = data['name'] passowrd = data['password'] age = data['age'] p = Profile(email=email, surname=surname, name=name, password=passowrd, age=age) p.save() return HttpResponse('created/updated ' + email) except: error = 'missing informations' if request.method == 'DELETE': email = data['email'] try: p = Profile.objects.filter(email=email)[0].delete() except: error = 'Profile ' + email + ' dose not exist.' return HttpResponse('deleted ' + email) except: return HttpResponse('Bad Json')
def profile_edit(request): token = request.POST.get('token') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') info = request.POST.get('info') email = request.POST.get('email') file = request.FILES.get('file') roles = request.POST.get('roles') try: obj_token = Token.objects.get(token=token) try: user = User.objects.get(username=obj_token.user.username) # save profile try: profile = Profile.objects.get(user__username=user.username) url_image = str(profile.image) if os.path.exists(url_image): os.remove(url_image) except Profile.DoesNotExist: profile = Profile(user=user) profile.info = info if file != None: profile.image = file profile.save() # save user user.first_name = first_name user.last_name = last_name user.email = email try: user.save() user.groups.clear() group = Group.objects.get(name=roles) group.user_set.add(user) response = {'result': 1, 'message': 'Save success'} except Group.DoesNotExist: group = None response = {'result': 0, 'message': 'Can not add group'} except User.DoesNotExist: response = {'result': 0, 'message': 'Error User'} except Token.DoesNotExist: response = {'result': 0, 'message': 'Error Token'} return JsonResponse(response)
def profile_register(user, profile_data): try: return profile.objects.get(pk=user.id) except ObjectDoesNotExist: try: profile_data['user']=user profile=Profile(**profile_data) profile.save() group=Group.objects.get(name=profile_data['role']+'_basic') group.user_set.add(user) return profile except: pass return None
def register(user_data, profile_data, group): """ Register user: user_data = {'username', 'email', 'password'} profile_data = {'role', 'position'} """ user_data['email'] = user_data['email'] user_data['username'] = user_data['username'] try: #Determine if email already exists. user_exists = User.objects.filter(email=user_data['email']) if user_exists: return { 'user': user_exists[0], 'is_new': False } #Determine if username already exists. username_exists = User.objects.filter(username=user_data['username']) if username_exists: return { 'user': username_exists[0], 'is_new': False } user = User.objects.create_user(**user_data) profile_data['user'] = user profile = Profile(**profile_data) profile.save() group = Group.objects.get(name=group) group.user_set.add(user) return { 'user': user, 'is_new': True } except e: print (str(e)) #raise Exception(e.message) return None
def register(user_data, profile_data, group): # user_data = {'username', 'email', 'password'} # profile_data = {'role', 'position'} first_name = user_data['first_name'] last_name = user_data['last_name'] username = user_data['username'] email = user_data['email'] password = user_data['password'] profile_data = {} try: # check if email already exists email_exists = User.objects.filter(email=user_data['email']) if email_exists: return {'email': email_exists[0], 'is_new': False} # check if username already exists username_exists = User.objects.filter( username=user_data['username']) if username_exists: return {'user': username_exists[0], 'is_new': False} user = User.objects.create_user(username, email, password, first_name=first_name, last_name=last_name) profile_data['owner'] = user profile = Profile(**profile_data) profile.save() # group is for different user levels (admin or non-admin) group = Group.objects.get(name=group) group.user_set.add(user) # return a dict return {'user': user, 'is_new': True} except Exception as e: print(str(e)) raise Exception(e) return None
def register_profile(): if request.method == 'POST': name = request.json.get("name", None) last_name = request.json.get("last_name", None) about_me = request.json.get("about_me", None) github = request.json.get("github", None) linkedin = request.json.get("linkedin", None) twitter = request.json.get("twitter", None) user_id = request.json.get("user_id", None) if not name: return "Email required", 401 username = request.json.get("username", None) if not last_name: return "Username required", 401 password = request.json.get("password", None) if not about_me: return "Password required", 401 if not github: return "Password required", 401 # email_query = User.query.filter_by(user_id=user_id).first() # if email_query: # return "This email has been already taken", 401 profile = Profile() profile.name = name profile.last_name = last_name profile.twitter = twitter profile.github = github profile.linkedin = linkedin profile.user_id = user_id profile.about_me = about_me profile.status = True db.session.add(profile) db.session.commit() response = {"msg": "Added successfully", "github": github} return jsonify(response), 200
def create_account(request): stripe.api_key = settings.STRIPE_KEY email = request.data.get("email", "") password = request.data.get("password", "") if not email: return Response({'error': 'The email field is missing.'}, status=status.HTTP_200_OK) if not password: return Response({'error': 'The password field is missing.'}, status=status.HTTP_200_OK) user = User.objects.filter(username=email) if user.exists(): return Response({'error': 'The profile already exists.'}, status=status.HTTP_200_OK) account = stripe.Account.create( type='standard', email=email, business_type='individual', ) user = User.objects.create_user(username=email, password=password) profile = Profile() profile.user = user profile.stripe_id = account.id profile.save() account_links = stripe.AccountLink.create( account=account.id, refresh_url=settings.BASE_URL + "login/" + email + "/", return_url=settings.BASE_URL + "login/" + email + "/", type='account_onboarding', ) return Response({'url': account_links.url}, status=status.HTTP_200_OK)
def post(self, request): print(request.data.get("username")) username = request.data.get("username") password = request.data.get("password") if User.objects.filter(username=username).exists(): content = {'message': 'User already exists', 'success': False} return Response(content) else: user, created = User.objects.get_or_create(username=username) user.set_password(password) user.first_name = request.data.get("first_name") user.last_name = request.data.get("last_name") user.is_staff = request.data.get("is_staff") user.save() profile = Profile(user=user,phone_number='') profile.save() content = {'message': 'Registered ok!', 'success': True} return Response(content)
"furui", "たかぽん", "マルコ", "エネル", "ひとみちゃん", "ヤッホー", "さわお", "よーへい", "ユキタ", "ガウディ", "サモトラケのニケ", "クロネッカー", "座敷わらしポンタ", "うさかめ", "やまねこ", ] for i, name in enumerate(userNames): user = User( email=f"vl2id0aow1qkrt{i+1}@nfakdls.com", fund=random.randint(1000000, 30000000), ) user.set_password("dammy") user.save() profile = Profile( name=name, user=user, ) profile.save()
def handle(self, *args, **options): # Admin a = Employee().create(username="******", password="******", charge="secretary", first_name="Administrador", last_name="de Aesculapius") a.user.is_superuser = True a.user.is_staff = True a.save() a.user.save() # Employees s = Employee().create(username="******", password="******", charge="secretary", first_name="Secretaria Marta", last_name="Mocha", email=None) s1 = Employee().create(username="******", password="******", charge="secretary", first_name="Secretaria Olga", last_name="Mora", email=None) d = Employee().create(username="******", password="******", charge="doctor", first_name="Medica Romina", last_name="Valestrini", email=None) d1 = Employee().create(username="******", password="******", charge="doctor", first_name="Medico Ricardo", last_name="Morales", email=None) d5 = Employee().create(username="******", password="******", charge="doctor", first_name="Medico Ricardao", last_name="Moraleas", email=None) d5.save() s.save() s1.save() d.save() d1.save() s.set_assist_ed(d) d1.set_assist_ed(s1) # Patients p = Profile(first_name="Diego", last_name="Velinsky") p1 = Profile(first_name="Maria", last_name="de la Fuente") p2 = Profile(first_name="Pedro", last_name="Pitaria") p.save() p1.save() p2.save() # Visits v = Visit(doctor=d, patient=p, detail="Tenia gripe y le di antibiotico") v1 = Visit(doctor=d, patient=p1, detail="Tenia fiebre y lo deje en cuarentena") v2 = Visit(doctor=d, patient=p2, detail="Le dolia la cabeza y le di bayaspirina") v3 = Visit(doctor=d1, patient=p, detail="Seguia con gripe y le di mas antibiotico") v4 = Visit(doctor=d1, patient=p, detail="La gripe no ceso y lo mande al hospital") v5 = Visit(doctor=d1, patient=p1, detail="Luego de la cuarentena murio") v.save() v1.save() v2.save() v3.save() v4.save() v5.save()
import pandas as pd from pandas import ExcelFile df = pd.read_excel('G:/Dropbox/Poker/Poker.xlsx', sheet_name='Placings Data') print(df.columns[7:-3]) for player in df.columns[7:-3]: try: u = Profile.objects.get(nickname=player) except: print("Create profile %s" % player) u = User(username=player) u.save() p = Profile(nickname=player, user=u) p.save() league = League.objects.all()[0] i = 0 for game in df[df.columns[0]]: print(game) host = df[df.columns[5]][i] timestamp = df[df.columns[6]][i] date = timestamp.to_pydatetime() stake = df[df.columns[1]][i] first = df[df.columns[2]][i] second = df[df.columns[3]][i] third = df[df.columns[4]][i] print(host)
import random import time from api.app import db from api.models import Report, Profile, Image LAT = 43.655305 LNG = -79.402269 if __name__ == "__main__": for i in range(2): p = Profile() p.license_plate = ''.join([random.choice('ABCDEFGHIJKLMNOP1234567890') for i in range(8)]) p.vehicle = ''.join(random.choice(['SUV', 'Sedan', 'Truck', 'Van'])) for j in range(random.randint(2, 4)): r = Report( reporter_id=random.randint(0, 345245), report_type=random.choice(['hit', 'witness', 'red-light', 'collision']), timestamp=1566682828+random.randint(-10000, 10000), longitude=LNG+(random.random()), latitude=LAT+(random.random()), analysis_complete=False, video_id=None ) db.session.add(r) db.session.commit() p.reports.append(r)
def import_data(request): form = ImportForm() if request.method == "POST": form = ImportForm(request.POST, request.FILES) if form.is_valid(): category = form.cleaned_data['category'] lines = process_csv_file(request, True) for line in lines: line = line.split(',') code = generate_student_code() admission_number = line[0] name = line[1].split(' ') first_name = name[0] last_name = name[1] date_of_birth = line[2] gender = line[3] school_class = line[4] stream = line[5] dormitory = line[6] religion = line[7] district = line[8] nationality = line[9] home_address = line[10] email = line[11] date_joined = line[12] class_joined = line[13] disabled = line[14] other_info = line[15] student_nin = line[16] school_id = 1 father_name = line[17] father_telephone = line[18] father_email = line[19] father_occupation = line[20] father_nin = line[21] mother_name = line[22] mother_telephone = line[23] mother_email = line[24] mother_occupation = line[25] mother_nin = line[26] if category == '1': student = Student(first_name=first_name, last_name=last_name, date_of_birth=date_of_birth, gender=gender, school_class=school_class, stream=stream, other_info=other_info, nin=student_nin, admission_number=admission_number, school_id=school_id, religion=religion, code=code) student.save() print(father_name) ''' add parents ''' if father_name: name = father_name.split(' ') user = User( email=father_email, username=father_email, is_active=False, first_name=name[0], last_name=name[1], ) user.save(commit=False) user.set_password('sw33th0m3') # user.save() father = Nok(name=father_name, student=student, occupation=father_occupation, relationship='Father', nin=father_nin, profile=Profile( user=user, type='Parent', )) father.save() if mother_name: name = mother_name.split(' ') user = User( email=mother_email, username=mother_email, is_active=False, first_name=name[0], last_name=name[1], ) user.save(commit=False) user.set_password('sw33th0m3') # user.save() mother = Nok(name=mother_name, student=student, occupation=mother_occupation, relationship='Mother', nin=mother_nin, profile=Profile( user=user, type='Parent', )) mother.save() return HttpResponseRedirect(reverse('thanks')) return render(request, 'admin/import.html', {'model': { 'form': form, 'action': 'import-data' }})