def sign_up(request): form = SignupForm() if (request.method == "POST"): form = SignupForm(request.POST) if (form.is_valid()): org = Organization(name=form.cleaned_data['org_name'], country=form.cleaned_data['org_country'], region=form.cleaned_data['org_region'], email=form.cleaned_data['org_email'], phone_num=form.cleaned_data['org_phone_num']) org.save() username = form.cleaned_data['admin_email'] password = form.cleaned_data['admin_password'] user = User.objects.create_user(username, form.cleaned_data['admin_email'], password) user.first_name = form.cleaned_data['admin_first_name'] user.last_name = form.cleaned_data['admin_last_name'] user.save() user_detail = UserDetail(role_id=1) user_detail.user_id = user.id user_detail.organization = org user_detail.save() user = authenticate(request, username=username, password=password) login(request, user) return redirect(f'/organization/{org.id}') context = {"form": form} return render(request, 'sign_up.html', context)
def handle(self, filename, *args, **options): for row in csv.DictReader(open(filename, 'r')): try: point = Point(float(row['longitude']), float(row['latitude']), srid=4326) except: self.stdout.write(u'Failed to get point for %s' % row['Name']) point = None organization = Organization( name=row['Name'], address_line1=row['Address'], city=row['City'], state_province=row['State'], postal_code=row['Zip'], email=row['Email'], phone=row['Phone #'], site_url=row['website'] or None, mission=row['Mission'] or None, centroid=point, ) try: organization.save() organization.sectors.add(*self.get_sectors(row['Food Sector(s)'])) organization.types.add(*self.get_types(row['Organization Type'])) except Exception: print 'Failed to save organization %s' % organization.name continue
def _prepare_organization_data(request): imgPath = Organization.get_every_organizations_paths_to_logos() acronyms = Organization.get_every_organizations_acronyms() context = { 'organizationsAcronym': acronyms, 'organizations_logo_path': imgPath, 'organizationsAcronymsAndPathToIMG': zip(acronyms, imgPath) } return context
def setUp(self): agency = Agency(name='General Services Administration') agency.save() self.user = User.objects.create(username='******', first_name='aaron', last_name='snow') self.billable_accounting_code = AccountingCode(code='abc', agency=agency, office='18F', billable=True) self.billable_accounting_code.save() self.non_billable_accounting_code = AccountingCode(code='def', agency=agency, office='18F', billable=False) self.non_billable_accounting_code.save() self.organization = Organization(name='test-org', active=True, description='a test org') self.organization.save() self.profit_loss_account = ProfitLossAccount( name='PIF', accounting_string='This_is_a_string', as_start_date=datetime.date(2016, 10, 1), as_end_date=datetime.date(2017, 9, 30)) self.profit_loss_account.save() self.project = Project(accounting_code=self.billable_accounting_code, profit_loss_account=self.profit_loss_account, name='Test Project', start_date='2016-01-01', end_date='2016-02-01', agreement_URL='https://thisisaurl.com', project_lead=self.user) self.project.save() self.project_no_url = Project( accounting_code=self.billable_accounting_code, name='Test_no_url Project', start_date='2016-02-01', end_date='2016-02-02', agreement_URL='', project_lead=self.user) self.project_no_url.save() self.project_no_lead = Project( accounting_code=self.billable_accounting_code, name='Test_no_url Project', start_date='2016-02-01', end_date='2016-02-02', agreement_URL='https://thisisaurl.com', project_lead=None) self.project_no_lead.save() self.app.set_user(self.user)
def register_company(self, request, **kwargs): corporate_name = kwargs['corporate_name'] short_name = kwargs['short_name'] website = kwargs.get('website', None) company_phone = kwargs.get('company_phone', None) company_email = kwargs['company_email'] password = kwargs['password1'] contact_person = kwargs['contact_person'] contact_person_phone = kwargs.get('contact_person_phone', None) contact_person_email = kwargs['contact_person_email'] contact_person_position = kwargs.get('contact_person_position', None) if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) new_user = RegistrationProfile.objects.create_inactive_user( company_email, company_email, password, site, send_email=False ) new_user.first_name = short_name new_user.save() new_profile = UserProfile(user=new_user, is_organization=True) new_organization = Organization( user=new_user, corporate_name=corporate_name, short_name=short_name, website=website, company_phone=company_phone, company_email=company_email, contact_person=contact_person, contact_person_phone=contact_person_phone, contact_person_email=contact_person_email, contact_person_position=contact_person_position, approved=False ) new_organization.save() new_profile.organization = new_organization new_profile.save() signals.user_registered.send( sender=self.__class__, user=new_user, request=request ) return new_user
def contributor(): """Generates a valid and active contributor.""" # We may need an OrganizationFactory when the organizations app has a test suite sample_org = Organization(name="Sample org") sample_org.save() user = ContributorFactory() user.beneficiary_organization = sample_org user.save() return user
def setUp(self): """ Configure shared test data """ super().setUp() self.course_key = CourseKey.from_string("course-v1:Test+Course+Configured") self.course_key_with_defaults = CourseKey.from_string("course-v1:TestX+Course+Configured") self.organization = Organization(short_name=self.course_key.org) self.organization.save() self.provider_allowed = SUPPORTED_PROVIDERS[0] self.provider_denied = SUPPORTED_PROVIDERS[1]
def _create_organization(name, website_url): org = Organization(name=name, website_url=website_url) org.save() od = OrganizationDescription(organization=org) od.save() oc = OrganizationCheck(organization=org) oc.save() return org
def get_my_orgs(request, an_user=None): if request is not None and an_user is None: an_user = request.user orgs = Organization.objects.filter(users=an_user) if not orgs: default_org = Organization(slug='3bot', name="3bot") default_org.save() org_user = OrganizationUser(organization=default_org, user=an_user, is_admin=True) org_user.save() org_owner = OrganizationOwner(organization=default_org, organization_user=org_user) org_owner.save() orgs = Organization.objects.filter(users=an_user) return orgs
def annotator2_client(client): # we work in empty database, so let's create business user and login client = deepcopy(client) email = '*****@*****.**' password = '******' user = User.objects.create(email=email) user.set_password(password) # set password without hash user.save() business = create_business(user) Organization.create_organization(created_by=user, title=user.first_name) assert signin(client, email, password).status_code == 302 client.user = user client.annotator = user return client
def user_login(request): """ Login page """ user = request.user next_page = request.GET.get('next') next_page = next_page if next_page else reverse('projects:project-index') form = forms.LoginForm() if user.is_authenticated: return redirect(next_page) if request.method == 'POST': form = forms.LoginForm(request.POST) if form.is_valid(): user = form.cleaned_data['user'] auth.login(request, user, backend='django.contrib.auth.backends.ModelBackend') # user is organization member org_pk = Organization.find_by_user(user).pk request.session['organization_pk'] = org_pk request.session.modified = True return redirect(next_page) return render(request, 'users/user_login.html', { 'form': form, 'next': next_page })
def usage(request): if request.user.is_anonymous(): organizations = None else: organizations = Organization.getOrganizationsForUser( request.user ) return render_to_response("usage_restrictions.html", {"organizations":organizations}, context_instance=RequestContext(request))
def activity_subscriptions(request): organizations = Organization.getOrganizationsForUser(request.user) subscription_objs = ProjectEmailSubscription.objects.filter( user=request.user) if request.method == "POST": subscriptions = request.POST.getlist('subscriptions') subscriptions = [int(sub) for sub in subscriptions] # remove any unchecked... for old_sub in subscription_objs: if not old_sub.project.id in subscriptions: old_sub.delete() # add any new ones for new_sub in subscriptions: if len([ sub for sub in subscription_objs if sub.project.id == new_sub ]) == 0: project = Project.objects.get(id=new_sub) s = ProjectEmailSubscription(user=request.user, project=project) s.save() else: subscriptions = [sub.project.id for sub in subscription_objs] return render_to_response("activities/email_subscription.html", { "organizations": organizations, "subscriptions": subscriptions }, context_instance=RequestContext(request))
def user_login(request): """ Login page """ user = request.user next_page = request.GET.get('next') next_page = next_page if next_page else reverse('projects:project-index') login_form = load_func(settings.USER_LOGIN_FORM) form = login_form() if user.is_authenticated: return redirect(next_page) if request.method == 'POST': form = login_form(request.POST) if form.is_valid(): user = form.cleaned_data['user'] auth.login(request, user, backend='django.contrib.auth.backends.ModelBackend') # user is organization member org_pk = Organization.find_by_user(user).pk user.active_organization_id = org_pk user.save(update_fields=['active_organization']) return redirect(next_page) return render(request, 'users/user_login.html', { 'form': form, 'next': next_page })
def project_admin( request, group_slug ): project = get_object_or_404( Project, slug=group_slug ) admin_access_or_403(project, request.user ) form = ProjectOptionsForm(instance=project) adduser_form = AddUserForm(project=project, user=request.user) if request.method == 'POST': # If one of the three forms on the page has been submitted... if request.POST.get("action") == "updateProject": form = ProjectOptionsForm( request.POST, instance=project) if form.is_valid(): # All validation rules pass form.save() request.user.message_set.create(message="Project options Saved.") return HttpResponseRedirect(reverse("project_detail",kwargs={'group_slug':project.slug})) if request.POST.get("action") == "moveToOrganization": organization = get_object_or_404( Organization, id=request.POST.get("organization_id","")) if project.organization: for team in project.organization.teams.all(): if project in team.projects.all(): team.projects.remove(project) project.organization = organization project.save() owners = organization.getOwnersGroup() if owners: owners.projects.add(project) request.user.message_set.create(message="Project moved to organization") return HttpResponseRedirect(reverse("organization_detail",kwargs={'organization_slug':organization.slug})) # if request.POST.get("action") == "removeFromOrganization": # if request.POST.get("remove") == "on": # for team in project.organization.teams.all(): # if project in team.projects.all(): # team.projects.remove(project) # project.organization = None # project.save() # request.user.message_set.create(message="Project removed from organization") if request.POST.get("action") == "add": write_access_or_403(project, request.user ) adduser_form = AddUserForm(request.POST, project=project, user=request.user) if adduser_form.is_valid(): adduser_form.save(request.user) return HttpResponseRedirect( reverse("project_admin", kwargs={"group_slug":project.slug} ) ) if request.POST.get("action") == "archiveProject": project.active = False project.save() return HttpResponseRedirect( reverse("project_detail", kwargs={"group_slug":project.slug} ) ) organizations = Organization.getAdminOrganizationsForUser(request.user) return render_to_response("projects/project_admin.html", { "project": project, "form": form, "adduser_form": adduser_form, "organizations": organizations }, context_instance=RequestContext(request))
def activity_subscriptions(request): organizations = Organization.getOrganizationsForUser(request.user) subscription_objs = ProjectEmailSubscription.objects.filter(user=request.user) if request.method == "POST": subscriptions = request.POST.getlist("subscriptions") subscriptions = [int(sub) for sub in subscriptions] # remove any unchecked... for old_sub in subscription_objs: if not old_sub.project.id in subscriptions: old_sub.delete() # add any new ones for new_sub in subscriptions: if len([sub for sub in subscription_objs if sub.project.id == new_sub]) == 0: project = Project.objects.get(id=new_sub) s = ProjectEmailSubscription(user=request.user, project=project) s.save() else: subscriptions = [sub.project.id for sub in subscription_objs] return render_to_response( "activities/email_subscription.html", {"organizations": organizations, "subscriptions": subscriptions}, context_instance=RequestContext(request), )
def make_task(request): if request.user.is_authenticated: body = json.loads(request.body) title = body["title"] if "title" in body else None description = body["description"] if "description" in body else None organization = body["organization"] if "organization" in body and not body["noOrg"] else None owners = body["owners"] if organization: organization = Organization(id=organization) task = Task(title=title, description=description, organization=organization) task.save() owner_objs = [] result = [] if owners: for owner in owners: try: u = User.objects.get(pk=owner) result.append({"id":u.id, "username": u.username, "email": u.email}) owner_objs.append(u) except User.DoesNotExist: JsonResponse({'Error': 'One or more of these user dont exist'}, status=500) for obj in owner_objs: task.owners.add(obj) org_id = task.organization.id if task.organization else None task_obj = {"id": task.id, "title":task.title, "description":task.description, "organization":org_id, "owners": result} return JsonResponse(task_obj) else: JsonResponse({"Error": "User is not authenticated"}, status=500)
def _account_numbers_dict(account): start_of_this_year = datetime.date(month=1, day=1, year=datetime.date.today().year) total_donations = Donation.objects_by_account(account).filter(date__gte=start_of_this_year).count() if not total_donations: total_donations = 0 total_donors = Donation.objects_by_account(account).filter(date__gte=start_of_this_year).order_by().all().aggregate(Count('donor', distinct=True))["donor__count"] if not total_donors: total_donors = 0 total_donation_amount = Donation.objects_by_account(account).filter(date__gte=start_of_this_year).order_by().all().aggregate(Sum('amount'))["amount__sum"] if not total_donation_amount: total_donation_amount = 0 average_donation = Donation.objects_by_account(account).filter(date__gte=start_of_this_year).order_by().all().aggregate(Avg('amount'))["amount__avg"] if not average_donation: average_donation = 0 total_volunteer_hours = CompletedShift.objects_by_account(account).filter(date__gte=start_of_this_year).order_by().all().aggregate(Sum('duration'))["duration__sum"] if not total_volunteer_hours: total_volunteer_hours = 0 total_people = Person.objects_by_account(account).count() total_orgs = Organization.objects_by_account(account).count() total_groups = Group.objects_by_account(account).count() total_tags = Tag.objects_by_account(account).count() total_taggeditems = TaggedItem.objects_by_account(account).count() recent_conversations = Conversation.objects_by_account(account).all()[:5] return locals()
def _create_user(input_args, config): from users.models import User from organizations.models import Organization username = input_args.username or config.get('username') or get_env('USERNAME') password = input_args.password or config.get('password') or get_env('PASSWORD') token = input_args.user_token or config.get('user_token') or get_env('USER_TOKEN') if not username: user = User.objects.filter(email=DEFAULT_USERNAME).first() if user is not None: if password and not user.check_password(password): user.set_password(password) user.save() print(f'User {DEFAULT_USERNAME} password changed') return user print(f'Please enter default user email, or press Enter to use {DEFAULT_USERNAME}') username = input('Email: ') if not username: username = DEFAULT_USERNAME if not password: password = getpass.getpass(f'Default user password {DEFAULT_USERNAME}: ') try: user = User.objects.create_user(email=username, password=password) user.is_staff = True user.is_superuser = True user.save() if token and len(token) > 5: from rest_framework.authtoken.models import Token Token.objects.filter(key=user.auth_token.key).update(key=token) else: print(f"Token {token} is not applied to user {DEFAULT_USERNAME} " f"because it's empty or len(token) < 5") except IntegrityError: print('User {} already exists'.format(username)) user = User.objects.get(email=username) org = Organization.objects.first() if not org: Organization.create_organization(created_by=user, title='Label Studio') else: org.add_user(user) return user
def register_company(self, request, **kwargs): corporate_name = kwargs['corporate_name'] short_name = kwargs['short_name'] website = kwargs.get('website', None) company_phone = kwargs.get('company_phone', None) company_email = kwargs['company_email'] password = kwargs['password1'] contact_person = kwargs['contact_person'] contact_person_phone = kwargs.get('contact_person_phone', None) contact_person_email = kwargs['contact_person_email'] contact_person_position = kwargs.get('contact_person_position', None) if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) new_user = RegistrationProfile.objects.create_inactive_user( company_email, company_email, password, site, send_email=False) new_user.first_name = short_name new_user.save() new_profile = UserProfile(user=new_user, is_organization=True) new_organization = Organization( user=new_user, corporate_name=corporate_name, short_name=short_name, website=website, company_phone=company_phone, company_email=company_email, contact_person=contact_person, contact_person_phone=contact_person_phone, contact_person_email=contact_person_email, contact_person_position=contact_person_position, approved=False) new_organization.save() new_profile.organization = new_organization new_profile.save() signals.user_registered.send(sender=self.__class__, user=new_user, request=request) return new_user
def project_admin( request, group_slug ): project = get_object_or_404( Project, slug=group_slug ) admin_access_or_403(project, request.user ) form = ProjectOptionsForm(instance=project) adduser_form = AddUserForm(project=project, user=request.user) if request.method == 'POST': # If one of the three forms on the page has been submitted... if request.POST.get("action") == "updateProject": form = ProjectOptionsForm( request.POST, instance=project) if form.is_valid(): # All validation rules pass story = form.save( commit=False ) story.local_id = project.stories.count() + 1 story.project = project story.creator = request.user story.save() request.user.message_set.create(message="Project options Saved.") return HttpResponseRedirect(reverse("project_detail",kwargs={'group_slug':project.slug})) if request.POST.get("action") == "moveToOrganization": organization = get_object_or_404( Organization, id=request.POST.get("organization_id","")) project.organization = organization project.save() request.user.message_set.create(message="Project added to organization") return HttpResponseRedirect(reverse("organization_detail",kwargs={'organization_slug':organization.slug})) if request.POST.get("action") == "removeFromOrganization": if request.POST.get("remove") == "on": for team in project.organization.teams.all(): if project in team.projects.all(): team.projects.remove(project) project.organization = None project.save() request.user.message_set.create(message="Project removed from organization") if request.POST.get("action") == "add": write_access_or_403(project, request.user ) adduser_form = AddUserForm(request.POST, project=project, user=request.user) if adduser_form.is_valid(): adduser_form.save(request.user) return HttpResponseRedirect( reverse("project_admin", kwargs={"group_slug":project.slug} ) ) if request.POST.get("action") == "archiveProject": project.active = False project.save() return HttpResponseRedirect( reverse("project_detail", kwargs={"group_slug":project.slug} ) ) if project.organization: organizations = None else: organizations = Organization.getAdminOrganizationsForUser(request.user) return render_to_response("projects/project_admin.html", { "project": project, "form": form, "adduser_form": adduser_form, "organizations": organizations }, context_instance=RequestContext(request))
def save(self, *args, **kwargs): if self.pk == None: self.send_account_confirmation_email() if self.organization == None: self.organization = Organization.new_default_organization() return super().save()
def create(request, form_class=ProjectForm, template_name="projects/create.html"): project_form = form_class(request.POST or None) admin_organizations = Organization.getOrganizationsForUser( request.user ) # The user can create projects in organizations the user is an admin in. if project_form.is_valid(): project = project_form.save(commit=False) project.creator = request.user org_id = request.POST.get("organization", "none") organization = None if org_id != "none": organization = Organization.objects.filter(id=org_id)[0] creationAllowed = True if organization: creationAllowed = org_project_limit.increaseAllowed(organization=organization) else: creationAllowed = personal_project_limit.increaseAllowed(user=request.user) if creationAllowed: project.save() if organization != None: if ( organization in admin_organizations ): # make sure the specified organization is in the list of admin orgs, if not silently ignore it. addProjectToOrganization(project, organization) # We better make the user a member of their own project. project_member = ProjectMember(project=project, user=request.user) project.members.add(project_member) project_member.save() # And lets make the default backlog iteration with no start/end dates. default_iteration = Iteration(name="Backlog", detail="", default_iteration=True, project=project) project.iterations.add(default_iteration) default_iteration.save() request.user.message_set.create(message="Project Created") # Finished successfully creating a project, send the user to that page. return HttpResponseRedirect(project.get_absolute_url()) else: return HttpResponseRedirect(reverse("usage")) # If they got here from the organziation page, there will be an org get-param set stating what organization it was from. # we need that here so it's pre-selected in the form. organization = None if request.GET.get("org", "") != "": organization = Organization.objects.filter(id=request.GET.get("org", ""))[0] return render_to_response( template_name, {"project_form": project_form, "admin_organizations": admin_organizations, "organization": organization}, context_instance=RequestContext(request), )
def _create_user(input_args, config): from users.models import User from organizations.models import Organization DEFAULT_USERNAME = '******' username = input_args.username or config.get('username') or get_env( 'USERNAME') password = input_args.password or config.get('password') or get_env( 'PASSWORD') if not username: user = User.objects.filter(email=DEFAULT_USERNAME).first() if user is not None: if password and not user.check_password(password): user.set_password(password) user.save() print('User password changed') return user print( 'Please enter default user email, or press Enter to use "default_user@localhost"' ) username = input('Email: ') if not username: username = DEFAULT_USERNAME if not password: password = getpass.getpass('Default user password: '******'User {} already exists'.format(username)) user = User.objects.get(email=username) org = Organization.objects.first() if not org: Organization.create_organization(created_by=user, title='Label Studio') else: org.add_user(user) return user
def create(request, form_class=ProjectForm, template_name="projects/create.html"): project_form = form_class(request.POST or None) admin_organizations = Organization.getOrganizationsForUser( request.user ) # The user can create projects in organizations the user is an admin in. if project_form.is_valid(): project = project_form.save(commit=False) project.creator = request.user org_id = request.POST.get("organization","none") organization = None if org_id != "none": organization = Organization.objects.filter( id=org_id )[0] creationAllowed = True if organization: creationAllowed = org_project_limit.increaseAllowed(organization=organization) else: creationAllowed = personal_project_limit.increaseAllowed(user=request.user) if creationAllowed: project.save() if organization != None: if organization in admin_organizations: # make sure the specified organization is in the list of admin orgs, if not silently ignore it. addProjectToOrganization(project, organization) # We better make the user a member of their own project. project_member = ProjectMember(project=project, user=request.user) project.members.add(project_member) project_member.save() # And lets make the default backlog iteration with no start/end dates. default_iteration = Iteration( name='Backlog', detail='', default_iteration=True, project=project) project.iterations.add(default_iteration) default_iteration.save() request.user.message_set.create(message="Project Created") # Finished successfully creating a project, send the user to that page. return HttpResponseRedirect(project.get_absolute_url()) else: return HttpResponseRedirect( reverse("usage") ) # If they got here from the organziation page, there will be an org get-param set stating what organization it was from. # we need that here so it's pre-selected in the form. organization = None if request.GET.get("org","") != "": organization = Organization.objects.filter(id=request.GET.get("org",""))[0] return render_to_response(template_name, { "project_form": project_form, "admin_organizations":admin_organizations, "organization":organization }, context_instance=RequestContext(request))
def create_orgs(): names = ["Microsoft", "Google", "Intel"] emails = [ "*****@*****.**", "*****@*****.**", "*****@*****.**" ] orgs = [] print("Creating orgs") for i in range(0, 3): org = Organization(name=names[i], country="US", region="California", email=emails[i], phone_num="+12345678901") org.save() print( f"\tSaving Org: {names[i]}, US, California, {emails[i]}, +12345678901" ) orgs.append(org) return orgs
def test_status_is_set_in_decision_detail_context(self): """ Same as test_status_is_set_in_decision_list_context but for decision_detail view. """ dd = DecisionDetail() manual_status = 'i set the status' decision = Decision(status=manual_status, organization=Organization()) dd.object = decision context = dd.get_context_data() self.assertEqual(context['tab'], manual_status)
def project_admin(request, group_slug): project = get_object_or_404(Project, slug=group_slug) admin_access_or_403(project, request.user) form = ProjectOptionsForm(instance=project) if request.method == 'POST': # If one of the three forms on the page has been submitted... if request.POST.get("action") == "updateProject": form = ProjectOptionsForm(request.POST, instance=project) if form.is_valid(): # All validation rules pass story = form.save(commit=False) story.local_id = project.stories.count() + 1 story.project = project story.creator = request.user story.save() request.user.message_set.create( message="Project options Saved.") return HttpResponseRedirect( reverse("project_detail", kwargs={'group_slug': project.slug})) if request.POST.get("action") == "moveToOrganization": organization = get_object_or_404(Organization, id=request.POST.get( "organization_id", "")) project.organization = organization project.save() request.user.message_set.create( message="Project added to organization") return HttpResponseRedirect( reverse("organization_detail", kwargs={'organization_slug': organization.slug})) if request.POST.get("action") == "removeFromOrganization": if request.POST.get("remove") == "on": for team in project.organization.teams.all(): if project in team.projects.all(): team.projects.remove(project) project.organization = None project.save() request.user.message_set.create( message="Project removed from organization") if project.organization: organizations = None else: organizations = Organization.getAdminOrganizationsForUser(request.user) return render_to_response("projects/project_admin.html", { "project": project, "form": form, "organizations": organizations }, context_instance=RequestContext(request))
def make_annotator(config, project, login=False, client=None): from users.models import User user = User.objects.create(**config) user.set_password('12345') user.save() create_business(user) if login: Organization.create_organization(created_by=user, title=user.first_name) if client is None: client = Client() signin_status_code = signin(client, config['email'], '12345').status_code assert signin_status_code == 302, f'Sign-in status code: {signin_status_code}' project.add_collaborator(user) if login: client.annotator = user return client return user
def setUp(self): organization = Organization(name='name', address_line1='address', address_line2='', address_city='city', address_state='state', address_zip='zip', address_country='us', phone='phone') organization.save() organization2 = Organization(name='name2', address_line1='address2', address_line2='', address_city='city2', address_state='state2', address_zip='zip2', address_country='us2', phone='phone2') organization2.save() self.staff = User.objects.create_superuser('staff', '*****@*****.**', 'staffPassword') self.admin = User.objects.create_user('admin', '*****@*****.**', 'adminPassword') user = Profile(user=self.admin, is_admin=True, organization=organization) user.save() self.user = User.objects.create_user('user', '*****@*****.**', 'userPassword') user = Profile(user=self.user, is_admin=False, organization=organization) user.save() self.admin2 = User.objects.create_user('admin2', '*****@*****.**', 'admin2Password') user = Profile(user=self.admin2, is_admin=True, organization=organization2) user.save() self.admin3 = User.objects.create_user('admin3', '*****@*****.**', 'admin3Password') user = Profile(user=self.admin3, is_admin=True, organization=organization2) user.save()
def setup_project(client, project_template, do_auth=True): """ Create new [email protected] user, login via client, create test project. Project configs are thrown over params and automatically grabs from functions names started with 'project_' :param client: fixture with http client (from pytest-django package) and simulation of http server :param project_template: dict with project config :param do_auth: make authorization for creating user """ client = deepcopy(client) email = "*****@*****.**" password = "******" urls = URLS() project_config = project_template() # we work in empty database, so let's create business user and login user = User.objects.create(email=email) user.set_password(password) # set password without hash create_business(user) org = Organization.create_organization(created_by=user, title=user.first_name) user.active_organization = org user.save() if do_auth: assert signin(client, email, password).status_code == 302 # create project with requests_mock.Mocker() as m: m.register_uri('POST', re.compile(r'ml\.heartex\.net/\d+/validate'), text=json.dumps({'status': 'ok'})) m.register_uri('GET', re.compile(r'ml\.heartex\.net/\d+/health'), text=json.dumps({'status': 'UP'})) r = client.post(urls.project_create, data=project_config) print('Project create with status code:', r.status_code) assert r.status_code == 201, f'Create project result should be redirect to the next page' # get project id and prepare url project = Project.objects.filter(title=project_config['title']).first() urls.set_project(project.pk) print('Project id:', project.id) client.project = project client.user = user client.urls = urls client.project_config = project_config client.org = org return client
def create_organizations(self): if not Organization.organization_in_db("PK"): Organization(name="Politechnika Krakowska", acronym="PK").save() if not Organization.organization_in_db("UJ"): Organization(name="Uniwersytet Jagieloński ", acronym="UJ").save() if not Organization.organization_in_db("AGH"): Organization(name="Akademia Górniczo Hutnicza", acronym="AGH").save()
def home(request): my_projects = [] member_projects = [] organizations = [] activities = [] next_page = False if request.user.is_authenticated(): organizations = Organization.getOrganizationsForUser(request.user) activities = Activity.getActivitiesForUser(request.user) assigned_stories = Story.getAssignedStories(request.user) paginator = Paginator(activities, 10) page_obj = paginator.page(1) activities = page_obj.object_list next_page = page_obj.has_next() memberships = ProjectMember.objects.filter(user=request.user) for membership in memberships: try: if (membership.project.creator_id == request.user.id): my_projects.append(membership.project) else: member_projects.append(membership.project) except: pass num_projects = len(member_projects) + len( filter(lambda p: p.organization == None, my_projects)) blank_state = True if (num_projects + len(organizations)) == 0 else False return render_to_response( "homepage.html", { "my_projects": my_projects, "my_organizations": organizations, "activities": activities, "activities_next_page": next_page, "assigned_stories": assigned_stories, "return_type": "queue", # for the queue mini stories "member_projects": member_projects, "num_projects": num_projects, "now": datetime.datetime.now(), "blank_state": blank_state }, context_instance=RequestContext(request)) else: return render_to_response("unauthenticated_homepage.html", context_instance=RequestContext(request))
def home(request): my_projects = [] member_projects = [] organizations = [] activities = [] next_page = False if request.user.is_authenticated(): organizations = Organization.getOrganizationsForUser(request.user) activities = Activity.getActivitiesForUser(request.user) assigned_stories = Story.getAssignedStories(request.user) paginator = Paginator(activities, 10) page_obj = paginator.page(1) activities = page_obj.object_list next_page = page_obj.has_next() memberships = ProjectMember.objects.filter(user=request.user) for membership in memberships: try: if membership.project.creator_id == request.user.id: my_projects.append(membership.project) else: member_projects.append(membership.project) except: pass num_projects = len(member_projects) + len(filter(lambda p: p.organization == None, my_projects)) blank_state = True if (num_projects + len(organizations)) == 0 else False return render_to_response( "homepage.html", { "my_projects": my_projects, "my_organizations": organizations, "activities": activities, "activities_next_page": next_page, "assigned_stories": assigned_stories, "return_type": "queue", # for the queue mini stories "member_projects": member_projects, "num_projects": num_projects, "now": datetime.datetime.now(), "blank_state": blank_state, }, context_instance=RequestContext(request), ) else: return render_to_response("unauthenticated_homepage.html", context_instance=RequestContext(request))
def get_current_organization(request): """ Return a single organization for the current site. :param request: :raise Site.DoesNotExist when the site isn't found. :raise Organization.DoesNotExist when the organization isn't found. :raise Organization.MultipleObjectsReturned when more than one organization is returned. :return Organization. """ current_site = get_current_site(request) main_site_id = getattr(settings, 'SITE_ID', None) if main_site_id and current_site and current_site.id == main_site_id: raise Organization.DoesNotExist('Tahoe: Should not find organization of main site `settings.SITE_ID`') return Organization.objects.get(sites__in=[current_site])
def proceed_registration(request, user_form, organization_form, next_page): """ Register a new user for POST user_signup """ # save user to db user, redirect_url = save_user(request, next_page, user_form, organization_form) if Organization.objects.exists(): org = Organization.objects.first() org.add_user(user) else: org = Organization.create_organization(created_by=user, title='Label Studio') request.session['organization_pk'] = org.pk request.session.modified = True return redirect(redirect_url)
def home( request ): my_projects = []; member_projects = []; organizations = []; next_page = False if request.user.is_authenticated(): organizations = Organization.getOrganizationsForUser(request.user) if len(organizations) == 1: return HttpResponseRedirect(organizations[0].get_absolute_url()) return render_to_response("homepage.html", { "my_organizations": organizations, "now": datetime.datetime.now() }, context_instance=RequestContext(request)) else: return render_to_response("unauthenticated_homepage.html", context_instance=RequestContext(request))
def proceed_registration(request, user_form, organization_form, next_page): """ Register a new user for POST user_signup """ # save user to db save_user = load_func(settings.SAVE_USER) user, redirect_url = save_user(request, next_page, user_form, organization_form) if Organization.objects.exists(): org = Organization.objects.first() org.add_user(user) else: org = Organization.create_organization(created_by=user, title='Label Studio') user.active_organization = org user.save(update_fields=['active_organization']) return redirect(redirect_url)
reader = csv.reader(csvfile) lines = list(reader) for f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10 in lines: i += 1 print ("%s/%s" % (i, lines.__len__())) org_name = f1 org_add1 = f6 org_add2 = f7 org_city = f8 org_state = f9 org_zip = f10 org_office = f5 org = Organization() org.name = org_name org.add1 = org_add1 org.add2 = org_add2 org.city = org_city org.state = org_state org.zip = org_zip org.office = org_office org.save() print "Organizations - DONE" i = 0 # Create casting users. with open('data/__setc_casting_users__', 'rU') as csvfile: reader = csv.reader(csvfile)
def test_num_organizations(self): a = Factory.create_demo_site("test", quick=True) self.assertEqual(a.num_organizations, Organization.objects_by_account(a).count())