def signup(request): form = OrgSignUpForm() if request.method == 'POST': form = OrgSignUpForm(request.POST) if form.is_valid(): user = User() user.email = form.cleaned_data.get('email').lower() user.username = form.cleaned_data.get('email').lower()[:30] # TODO: fix it in #135 user.set_password(form.cleaned_data.get('password')) user.save() org = Organization(name=form.cleaned_data.get('organization_name')) org.save() _orgmem = OrganizationMember(user=user, is_owner=True, organization=org).save() token = Token(user=user, type='signup') token.save() link = request.build_absolute_uri(reverse('activate-account', args=[token.token])) send_mail('Account activation', settings.ACCOUNT_ACTIVATION_EMAIL % (org.name, link,), '*****@*****.**', [user.email, ]) # messages.add_message(request, messages.SUCCESS, # _('Please click the activation link which was sent to your email')) _user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password']) if _user is not None: # TODO: only sign in users which activated their account login(request, _user) messages.add_message(request, messages.SUCCESS, _('Please update your profile')) return redirect('settings') return redirect('/') return render(request, 'app/signup.html', locals())
def create_organization(request): if request.method == 'POST': email = request.data.get('email') password = request.data.get('password') country = request.data.get('country') name = request.data.get('name') if not validate_email(email): return Response(error_msg("Invalid email address."), status=status.HTTP_400_BAD_REQUEST) if len(password) < 6: return Response(error_msg( "Invalid password. Password should be greater than 5 characters." ), status=status.HTTP_400_BAD_REQUEST) try: User.objects.get(username=email) return Response(error_msg("User already exists."), status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: pass user = User.objects.create_user(username=email, email=email, password=password) user.first_name = email user.last_name = email user.save() organization = Organization(user=user, name=name, country=country) organization.save() serialized_org = OrganizationSerializer(organization) return Response(success_msg("Created organization successfully", serialized_org.data), status=status.HTTP_201_CREATED)
def add_organization(): params = request.form or request.get_json() or request.args name = params.get('name') remark = params.get('remark') username = params.get('username') password = params.get('password') if not name or not username or not password: return error_result(ErrorCode.ERROR_INVALID_PARAM) if Organization.query.filter_by(name=name).first() is not None: return error_result(ErrorCode.ERROR_ORGANIZATION_ALREADY_EXIST) if User.query.filter_by(username=username).first() is not None: return error_result(ErrorCode.ERROR_USERNAME_EXISTED) org = Organization(name=name, remark=remark, create_time=g.TIMESTAMP) db.session.add(org) db.session.commit() user = User(organization_id=org.id, role_id=UserRole.ROLE_ORGANIZATION, username=username, password=password, password_reseted=True) db.session.add(user) db.session.commit() ret = org.get_json() ret['username'] = username return success_result(ret)
def processCreate(name, address, contacts): """Creates a new user based on POST data""" newOrg = Organization(name=name, address=address) newOrg.save() Contact.update(organization=newOrg).where(Contact.id << contacts).execute() flash('Created %s' % name, 'success') return redirect(url_for('contacts.index'))
def add_org(uuid): """Adds new organization for given user. Receives - uuid: uuid4 [required - in URL] - start_date: date [required] - end_date: date [optional] - description: text [optional] - name: string [required] - address1: string [optional] - address2: string [optional] - city: string [optional] - state: string(2) [optional] - zipcode: string(5) [optional] - phone: string(10) [optional] - website: string(50) [optional] Creates new organization for with foreign key uuid. """ content = request.json print(content) if not content: abort(400) org = Organization(**content) pl.convert_to_date(org.start_date) pl.convert_to_date(org.end_date) org.uuid = uuid # try: print("here3") db.session.add(org) db.session.commit() return "New org, {}, added for uuid: {}".format(org.name, uuid)
def orgregister(): regform = OrgRegisterForm() loginform = OrgLogin() if regform.validate_on_submit(): NewOrg = Organization(org_name=regform.org_name.data, org_email=regform.org_email.data) NewOrg.set_password(regform.password.data) NewOrg.id = Organization.query.count() + 1 db.session.add(NewOrg) db.session.commit() user = NewOrg login_user(user) return redirect(url_for('orgprofile', org_id=NewOrg.id)) elif loginform.validate_on_submit(): user = Organization.query.filter_by( org_email=loginform.org_email.data).first() user_id = user.id #If the user is logged in if not user is None or not user.check_password( loginform.password.data): login_user(user) return redirect(url_for('orgprofile', org_id=user_id)) else: flash("Bad credentials") return render_template('orgregister.html', regform=regform, loginform=loginform)
def import_certs(collab_url, username, password): """Import national CERTs information from AbuseHelper collab wiki.""" if click.confirm("This command should be run only once, on install", abort=True): ah_resp = requests.get(collab_url, auth=(username, password), verify=False) if ah_resp.status_code != 200: current_app.log.error(ah_resp.reason) raise click.Abort data = json.loads(ah_resp.text) for country, details in data.items(): org = Organization(abbreviation=country, group_id=2, full_name='National CERT of ' + country) try: org.mail_times = details['Mail times'][0] except IndexError: current_app.log.debug('Using default mail times...') try: org.mail_template = details['Mail template'][0] except IndexError: current_app.log.debug('Using default template...') org.abuse_emails = details['Abuse email'] click.echo("Adding {}...".format(country)) db.session.add(org) db.session.commit() click.echo('Done')
def test_create_organization(client): neworg = Organization(full_name=TAU.orgname, display_name=TAU.orgname) neworg.abuse_emails = ['*****@*****.**'] db.session.add(neworg) db.session.commit() assert Organization.query.filter_by( full_name=TAU.orgname).first(), 'Organization not inserted.' assert TAU.testOneOrganization(), 'Organization exists multible times'
def processEdit(id, name, address, contacts): """Updates an Organization based on POST data""" Organization.update( name=name, address=address).where(Organization.id == id).execute() org = Organization.select().where(Organization.id == id).get() Contact.update(organization=None).where( Contact.organization == org).execute() Contact.update(organization=org).where(Contact.id << contacts).execute() flash('Organization %s updated' % name, 'success') return redirect(url_for('contacts.index'))
def add(): """Add sample data""" cert = Organization( abbreviation="CERT", full_name="CERT Master User", ) db.session.add(cert) cert_user = User(name="cert master user", ) cert_user.password = '******' db.session.add(cert_user) cert_user4cert = OrganizationMembership(email='*****@*****.**', zip='1234', organization=cert, user=cert_user) db.session.commit() click.echo('Done Org id: ' + str(cert.id)) click.echo('Done User id: ' + str(cert_user.id)) click.echo('adding sub org') eorg = Organization(abbreviation="E-Org", full_name="E-Org Dach", parent_org=cert) # db.session.add(eorg) eorg_user = User(name="eorg master user") eorg_user.password = '******' OrganizationMembership(email='*****@*****.**', zip='5678', organization=eorg, user=eorg_user) eorg_electricity = Organization(abbreviation="E-Org Strom", full_name="E-Org Strom", parent_org=eorg) db.session.add(eorg_electricity) eorg_electricity_user = User(name="eorg electricity user", ) eorg_electricity_user.password = '******' db.session.add(eorg_electricity_user) eorgelectricity_orguser = OrganizationMembership( email='*****@*****.**', zip='5678', organization=eorg_electricity, user=eorg_electricity_user) db.session.commit()
def signup(): if current_user.is_authenticated: return redirect('/') form = RegistrationForm() if form.validate_on_submit(): new_user = User(username=form.username.data, email=form.email.data) username = form.username.data new_user.set_password(form.password.data) if User.query.filter_by(username=form.username.data).first() is not None: flash('`Username taken') return redirect('/') if User.query.filter_by(email=form.email.data).first() is not None: flash('`That email is already associated with an account.') return redirect('/') db.session.add(new_user) db.session.commit() registered_user = User.query.filter_by(username=username).first() user_id = registered_user.id orglist = form.orgs.data print(orglist) print(user_id) for org in orglist: new_org_entry = Organization(user_id = user_id, org = org) db.session.add(new_org_entry) db.session.commit() login_user(new_user) flash('~Account ' + form.username.data + ' Created.') return redirect('/') else: flash_errors(form, '`') return redirect('/')
def test_organization(self): with self.app.app_context(): p0 = Person(first_name='zack', last_name='zhu') d0 = Dependent(first_name='adela', last_name='zhu') u0 = User(username='******', email='*****@*****.**', first_name='zack', last_name='zhu') u0.dependents.append(d0) # db.session.add(u0) # db.session.commit() org0 = Organization(name='Iceland', creator=u0) op0 = OrganizationPersonAssociation(organization=org0, associated_person=p0) op1 = OrganizationPersonAssociation(organization=org0, associated_person=u0) org0.organization_associations.append(op0) org0.organization_associations.append(op1) db.session.add(org0) db.session.commit() print(org0.organization_associations[0].associated_person) print(org0.organization_associations[1].associated_person) print(u0.organization_associations[0].organization) print(p0.organization_associations[0].organization) print(org0.organization_associations[:])
def register(): title = "Register Organization" formRegister = RegisterForm() if formRegister.validate_on_submit(): organization = Organization( name=formRegister.name_company.data, email=formRegister.email.data, typeofbusiness=formRegister.type_company.data, address=formRegister.address.data, phone_number=formRegister.business_phone_number.data) db.session.add(organization) db.session.commit() employee = Employee( fname=formRegister.manager_namef.data, lname=formRegister.manager_namel.data, email=formRegister.email.data, phone_number=formRegister.manager_phone_number.data, manager=True, organization_id=organization.id, firsttimelogin=False, question1=formRegister.question1.data, answer1=formRegister.answer1.data, question2=formRegister.question2.data, answer2=formRegister.answer2.data, ) employee.set_password(formRegister.enter_password.data) db.session.add(employee) db.session.commit() flash('New Organization has been added') return redirect(url_for('login')) return render_template("register.html", title=title, formRegister=formRegister)
def post_org(request): try: org_name = request.form.get('org_name') org_domain = request.form.get('org_domain') org_address = request.form.get('org_address') org_country = request.form.get('org_country') org_phone = request.form.get('org_phone', '') org_email = request.form.get('org_email', '') org_contact = request.form.get('org_contact', '') org = Organization(org_name=org_name, org_domain=org_domain, org_address=org_address, org_country=org_country, org_phone=org_phone, org_email=org_email, org_contact=org_contact) db.session.add(org) db.session.commit() return dict(status='OK', message='Orgnization created successfully.', error=None) except IntegrityError as e: return dict(status='FAIL', message='A similar organization already exists.', error=str(e)) except Exception as e: return dict(status='FAIL', message='Could not create organization.', error=str(e))
def test_store_existing_user(client, caplog): """End-to-end test of submitting the /validate-basic-info route with an existing user and an existing organization.""" existing_org = Organization(name='Foo Bar', financial_classification='', coverage_scope='', coverage_focus='', platform='', employee_range='', budget='', affiliations='') db.session.add(existing_org) existing_user = AppUser(name='Foo', email='*****@*****.**', email_hash='f3ada405ce890b6f8204094deb12d8a8', approved=True, orgs=[existing_org]) db.session.add(existing_user) db.session.commit() userform = ImmutableMultiDict([('name', 'bar'), ('email', '*****@*****.**'), ('news_org', 'foo bar')]) response = client.post('/validate-basic-info', data=userform) user = AppUser.query.filter_by(email='*****@*****.**').first() assert user.name == 'Bar' assert len(user.orgs) == 1 assert user.orgs[0].name == 'Foo Bar' assert response.get_json()['user'] == 'approved' assert ('Suppressing an email with the following params: ' 'Sender: [email protected]. Recipients: [\'[email protected]\']. ' 'Subject: You\'re all set to access our benchmarks!' in caplog.text)
def import_orgs(collab_url, username, password): """Import customers from AbuseHelper collab wiki.""" group_count = OrganizationGroup.query.count() if group_count < 1: sys.exit("No groups defined. " "Run create_groups to create default groups.") if click.confirm("This command will drop all exiting organizations" " and all their details (IPs, Emails, ASNs, etc.). " "Are you sure you want to continue?", abort=True): ah_resp = requests.get(collab_url, auth=(username, password), verify=False) if ah_resp.status_code != 201: current_app.log.error(ah_resp.reason) raise click.Abort click.echo("Deleting old data...") db.session.execute(emails_organizations.delete()) db.session.execute(tags_vulnerabilities.delete()) ContactEmail.query.delete() IpRange.query.delete() Fqdn.query.delete() Asn.query.delete() Email.query.delete() Vulnerability.query.delete() Organization.query.filter(Organization.group_id == 1).delete() click.echo("Old data deleted!") data = json.loads(ah_resp.text) for name, config in data.items(): org = Organization.from_collab(CollabCustomer(name, config)) click.echo("Adding {}...".format(org.abbreviation)) db.session.add(org) db.session.commit() click.echo('Done')
def post(self, request): data = json.loads(request.body) blogpost = self._get_post(data.get('id'), request.user) blogpost.title = data.get('title', '') blogpost.body = data.get('body', '') blogpost.published = data.get('published') posted_to = data.get('posted_to') if posted_to == 'organization': content_object = Organization.get_single_by_user(request.user) else: posted_to_id = int(data.get('posted_to_id')) content_object = Team.objects.get(pk=posted_to_id) # TODO: validate team blogpost.content_object = content_object blogpost.save() blogpost.tags.clear() tags = data.get('tags', []) for _tag in tags: slug = slugify(_tag.get('text', '')) try: tag = Tag.objects.get(slug=slug) except Tag.DoesNotExist: tag = Tag() tag.text =_tag.get('text', '') tag.save() blogpost.tags.add(tag) return json_response(blogpost.to_dict())
def addsampledata(): """Add sample data""" OrganizationGroup._OrganizationGroup__insert_defaults() ReportType._ReportType__insert_defaults() Role._Role__insert_defaults() Country._Country__insert_defaults() MembershipRole._MembershipRole__insert_defaults() adm = Role.query.filter_by(permissions=0xff).first() o = Organization( abbreviation="CERT-EU", full_name="Computer Emergency Response Team for EU " "Institutions Agencies and Bodies", ip_ranges=['212.8.189.16/28'], abuse_emails=['*****@*****.**'], contact_emails=[ContactEmail(email='*****@*****.**')], asns=[5400], fqdns=['cert.europa.eu']) db.session.add(o) db.session.commit() user = User(name='testadmin', email='*****@*****.**', password='******', role=adm) db.session.add(user) db.session.commit() click.echo('Done')
def show_register(request): if request.method == 'GET': errors = None if request.GET.get('errors') == '1': errors = 'Email already exists. Please try again.' elif request.GET.get('errors') == '2': errors = 'Country already have CDC registered. Please contact us if this is a mistake.' elif request.GET.get('errors') == '3': errors = 'Invalid email address.' elif request.GET.get('errors') == '4': errors = 'Password should be more than 5 characters.' return render(request, 'backend/register.html', {'errors': errors}) elif request.method == 'POST': organization = request.POST.get('organization') email = request.POST.get('email') password = request.POST.get('password') country = request.POST.get('country') if not validate_email(email): return HttpResponseRedirect('/new-cdc?errors=3') if len(password) < 6: return HttpResponseRedirect('/new-cdc?errors=4') try: User.objects.get(username=email) return HttpResponseRedirect('/new-cdc?errors=1') except User.DoesNotExist: pass try: Organization.objects.get(country=country) return HttpResponseRedirect('/new-cdc?errors=2') except Organization.DoesNotExist: pass user = User.objects.create_user(username=email, email=email) user.save() user.set_password(password) user.save() organization = Organization(user=user, name=organization, country=country) organization.save() user = authenticate(username=email, password=password) if user is not None: login(request, user) else: return HttpResponseRedirect('/login-cdc/') return HttpResponseRedirect('/dashboard/')
def organization(app): organization = Organization( uuid=uuid.uuid4().hex, name="test org", ) db.session.add(organization) db.session.commit() return organization
def create_org(): form = CreateOrganizationForm() if request.method == "GET": return render_template("createOrganization.html", user=current_user, form=form) if form.validate_on_submit(): org = Organization(name=form.name.data, website=form.website.data, mission=form.mission.data) if org.exists(): flash("Company with that name already exists") else: org.save() flash("Organization created for {}".format(org.name)) return redirect(url_for('home')) return render_template("createOrganization.html", user=current_user, form=form)
def seed(): project = Project(name="Test Project", description="Test description.....", image_url="https://source.unsplash.com/random") db.session.add(project) org = Organization(name="Test Org", description="Test description.....", image_url="https://source.unsplash.com/random") db.session.add(org) db.session.commit()
def index(): """Lists all contacts""" orgs = Organization.select().where(Organization.isDeleted == False) contacts = Contact.select().where(Contact.isDeleted == False) org_contacts = prefetch(orgs, contacts) contacts = Contact.select().where(Contact.organization == None, Contact.isDeleted == False) return render_template('admin/contacts/index.html', organizations=org_contacts, contacts=contacts)
def edit(id): """Displays an organizations information in a form""" org = Organization.select().where(Organization.id == id).get() return render_template( 'admin/organizations/edit.html', org=org, contacts=Contact.select().where(( (Contact.organization == None) | (Contact.organization == org) & (Contact.isDeleted == False)) | (Contact.organization_id == id)))
def new_organization(): form = NewOrganizationForm() if form.validate_on_submit(): o = Organization(creator_id=current_user.id, orgname=form.orgname.data, description=form.description.data) db.session.add(o) db.session.commit() return redirect(url_for('organizations')) return render_template('neworg.html', title='New Organization', form=form)
def get_logs(request): level = request.GET.get('level', 'user') page = int(request.GET.get('page', 0)) if page < 1: page = 1 per_page = 20 # TODO: move to settings entries = [] total = 0 organization = Organization.get_single_by_user(request.user) logs = [] blogposts = [] object_ids = [] if level == 'user': object = request.user object_type = ContentType.objects.get_for_model(object) object_ids = [request.user.id,] elif level == 'organization': teams = Team.objects.filter(organization=organization) if len(teams) == 0: return empty_set() object_type = ContentType.objects.get_for_model(teams[0]) object_ids = [team.id for team in teams] blogposts = Post.objects.filter(deleted=False, published=True, content_type__pk=ContentType.objects.get_for_model(organization).id, object_id=organization.pk) | Post.objects.filter(deleted=False, published=True, content_type__pk=object_type.id, object_id__in=object_ids) elif level == 'my-teams': teams = [membership.team for membership in Member.objects.filter(user=request.user)] if len(teams) == 0: return empty_set() object_type = ContentType.objects.get_for_model(teams[0]) object_ids = [team.id for team in teams] blogposts = Post.objects.filter(deleted=False, published=True, content_type__pk=object_type.id, object_id__in=object_ids) else: return json_response(status=400) logs = LoggedAction.objects.filter(content_type__pk=object_type.id, object_id__in=object_ids) | LoggedAction.objects.filter(content_type__pk=ContentType.objects.get_for_model(request.user).id, object_id__in=[request.user.id,]) items = sorted( chain(logs, blogposts), key=attrgetter('created_at'), reverse=True) paginator = Paginator(items, per_page) page_contents = paginator.page(page) total = paginator.count entries = [entry.to_dict() for entry in page_contents.object_list] return json_response({'entries': entries, 'total': total})
def edit(id): """View to display contact data""" contact = Contact.select().where(Contact.id == id).get() orgs = {0: "None"} for org in Organization.select().where( (Organization.isDeleted == False) | (Organization.id == contact.organization_id)): orgs[org.id] = org.name return render_template('admin/contacts/edit.html', contact=contact, orgs=orgs)
def add_organization(): form = OrgCreateForm() users = User.query.all() # empty_choice = [(0, " " * 10)] form.users.choices = [(user.id, user.email) for user in users] if form.validate_on_submit(): org = Organization(name=form.name.data, data_dir=form.data_dir.data) users = [] for user_id in form.users.data: user = User.query.filter_by(id=user_id).first() users.append(user) org.users = users session_add(org) session_commit() return redirect(url_for("admin.add_organization")) return render_template("admin_panel/create_organization.html", form=form)
def orgindex(orgid, includeCanceled=True, start=None, end=None): """List all bookings for an organization""" if start is None: start = date.today() if end is None: end = date.today() + timedelta(days=30) b = (Booking.select(Booking).join(Contact).where( Contact.organization_id == orgid).where((Booking.startTime > start) & (Booking.endTime < end))) if not includeCanceled: b = b.where(Booking.isCanceled == False) if orgid != 0: org = Organization.select().where(Organization.id == orgid).get() else: org = Organization(name="No Organization") bookings = prefetch(b, BookingRoom, Room, Contact) return render_template('bookings/orgIndex.html', bookings=bookings, start=start, end=end, includeCanceled=includeCanceled, org=org)
def update_organization(request): if request.method == 'POST': organization = Organization.get_single_by_user(request.user) logo = request.FILES.get('orglogo') menu_color = request.POST.get('menu_color') if logo is not None: organization.logo = logo if menu_color is not None: organization.menu_color = menu_color organization.save() messages.add_message(request, messages.SUCCESS, '%s organization was updated successfully' % (organization.name,)) return redirect(reverse('index')) raise Http404
def handle(self, *args, **options): if options['empty']: Organization.objects.all().delete() else: for data in get_api_data(): organization = Organization(**data) latitude, longitude = get_coordinates( organization.full_address()) organization.latitude = latitude organization.longitude = longitude organization.save()
def organization_create(auth_user): with WriteSession(closing=True) as session: organization = Organization.from_request(request.json) if session.query(Organization).filter(Organization.slug == organization.slug).first(): abort(400, {'message': "An organization by that name already exists", 'code': 400, 'data': {'name': organization.name, 'slug': organization.slug}}) org_user = OrganizationUser( role='administrator', organization=organization, user=auth_user ) session.add(organization) session.add(org_user) session.commit() return organization.to_json()
def post(self): json_data = request.get_json() if not json_data: raise RequestException("No input data", 400) try: data = organization_schema.load(json_data) except ValidationError as err: raise RequestException("Invalid input data", 400, err.messages) organization = Organization.create(**data) result = organization_schema.dump(organization) response = jsonify( {APIConst.MESSAGE: 'created new organization', APIConst.DATA: result}) return response
def get(self, request, team_id=None): if team_id is not None: return self.get_single(request, team_id) organization = Organization.get_single_by_user(request.user) teams = Team.objects.filter(organization=organization) if request.GET.get('myteams') is not None: entries = [team.to_dict() for team in teams if request.user in team.members] else: entries = [team.to_dict() for team in teams] response = { 'total': len(teams), 'entries': entries, } return json_response(response)
def addsampledata(client): """Add sample testing data""" OrganizationGroup._OrganizationGroup__insert_defaults() ReportType._ReportType__insert_defaults() Role._Role__insert_defaults() o = Organization( abbreviation="CERT-EU", full_name="Computer Emergency Response Team for EU " "Institutions Agencies and Bodies", ip_ranges=['212.8.189.16/28'], abuse_emails=['*****@*****.**'], contact_emails=[ContactEmail(email='*****@*****.**')], asns=[5400], fqdns=['cert.europa.eu']) _db.session.add(o) _db.session.commit()
def topOrgData(start, end): return (Organization.select( Organization, fn.Sum(Booking.finalPrice).alias('TotalSpend'), fn.Sum(Booking.catereringTotal).alias('TotalCaterering'), fn.Sum(Booking.roomTotal).alias('TotalRooms'), fn.Sum(Booking.discountTotal).alias('TotalDiscounts')).join( Contact, on=Contact.organization_id == Organization.id, join_type=JOIN.LEFT_OUTER).join( Booking, on=Booking.contact_id == Contact.id, join_type=JOIN.LEFT_OUTER).where((Booking.startTime >= start) & (Booking.startTime <= end)). group_by(Organization).order_by(fn.Sum( Booking.finalPrice).desc()).limit(10))
def validate(self): if not Form.validate(self): return False if self.name.data == self.original_name: return True if self.name.data != Organization.make_valid_name(self.name.data): self.name.errors.append(gettext('This name has invalid characters. Please use letters, numbers, dots and underscores only.')) return False user = User.query.filter_by(nickname = self.user_name).first() if user == None: self.name.errors.append(gettext('The user name was not found')) return False org = user.settings.filter_by(name = self.name.data).first() if org != None: self.name.errors.append(gettext('The Organization name already exists')) return False return True
def get(self, request, entry_id=None): if entry_id is not None: return self.get_single(request, entry_id) page = int(request.GET.get('page', 0)) if page < 1: page = 1 per_page = 20 # TODO: move to settings entries = [] total = 0 if request.GET.get('own') is not None: posts = Post.objects.filter(user=request.user, deleted=False) else: organization = Organization.get_single_by_user(request.user) teams = Team.objects.filter(organization=organization) if len(teams) == 0: return empty_set() object_type = ContentType.objects.get_for_model(teams[0]) object_ids = [team.id for team in teams] posts = Post.objects.filter(deleted=False, published=True, content_type__pk=ContentType.objects.get_for_model(organization).id, object_id=organization.pk) | Post.objects.filter(deleted=False, published=True, content_type__pk=object_type.id, object_id__in=object_ids) _tag = request.GET.get('tag') if _tag is not None: try: tag = Tag.objects.get(slug=_tag) except Tag.DoesNotExist: tag = None if tag is not None: posts = posts.filter(tags__in=[tag,]) posts = posts.order_by('-created_at') paginator = Paginator(posts, per_page) page_contents = paginator.page(page) total = paginator.count pages = paginator.num_pages entries = [blogpost.to_dict() for blogpost in page_contents.object_list] return json_response({'entries': entries, 'total': total, 'pages': pages})
def search(request): response = { 'entries': [], 'total': 0 } organization = Organization.get_single_by_user(request.user) users = [ms.user.to_dict() for ms in OrganizationMember.objects.filter(organization=organization)] for entry in users: entry['type'] = 'user' response['entries'] += users teams = [team.to_dict() for team in Team.objects.filter(organization=organization)] for entry in teams: entry['type'] = 'team' response['entries'] += teams roles = [role.to_dict() for role in Role.objects.filter(end_date__gt=datetime.datetime.now(), team_id__in=[team['id'] for team in teams])] for entry in roles: entry['type'] = 'role' response['entries'] += roles return json_response(response)
def get_my_organization(request): try: organization = Organization.get_single_by_user(request.user) except TypeError: return json_response(organization.to_dict()) return json_response(organization.to_dict())
def searchpeople(request): organization = Organization.get_single_by_user(request.user) peoples = [membership.user for membership in organization.members] teams = organization.team_set.all() return render(request, 'app/people.html', locals())
def handle(self, *args, **options): if options['apt_filename']: data_filename = os.getcwd() + '/app/'+options['apt_filename'] with open(data_filename, 'rb') as csv_read: read_data = csv.reader(csv_read, delimiter='#', quotechar='"') for row in read_data: apt = Apartment( address=row[0], district=row[1], rooms_num=row[2], month_price=row[3], floor=row[4], storeys_num=row[5], description=row[6], phone_number=row[7], location=fromstr("POINT(%s)" % (row[8]))) try: apt.save() except Exception as error: print "ERROR: %s" % error continue csv_read.close() elif options['org_filename']: data_filename = os.getcwd() + '/app/'+options['org_filename'] with open(data_filename, 'rb') as csv_read: read_data = csv.reader(csv_read, delimiter='#', quotechar='"') for row in read_data: org_type = row[0] if org_type == 'Детские сады / Ясли': org = Organization( type='KIN', name=row[1], address=row[2], location=fromstr("POINT(%s)" % (row[3]))) elif org_type == 'школы': org = Organization( type='SCH', name=row[1], address=row[2], location=fromstr("POINT(%s)" % (row[3]))) elif org_type == 'университеты': org = Organization( type='UNI', name=row[1], address=row[2], location=fromstr("POINT(%s)" % (row[3]))) elif org_type == 'больницы': org = Organization( type='HOS', name=row[1], address=row[2], location=fromstr("POINT(%s)" % (row[3]))) elif org_type == 'фитнес-клубы': org = Organization( type='FIT', name=row[1], address=row[2], location=fromstr("POINT(%s)" % (row[3]))) else: org = Organization( type='SHP', name=row[1], address=row[2], location=fromstr("POINT(%s)" % (row[3]))) try: org.save() except Exception as error: print "ERROR: %s" % error continue csv_read.close() else: raise CommandError("One of the options `--apt_filename=...` or `--org_filename` must be specified.")
def refresh_orgs(): """Refresh all organizations from Trello""" for org_json in trello.get_organizations(): Organization.get_or_create(org_json) db.session.commit()