Exemplo n.º 1
0
 def _create_people(self):
     self.people = []
     for i in range(1, 4):
         person_name = 'Person ' + str(i)
         person = Person(name=person_name, rate=i)
         person.save()
         self.people.append(person)
Exemplo n.º 2
0
def add_user(req):
    user = req.user
    stub = user.username.split('@')[0]
    user.email = req.POST['email']
    user.first_name = req.POST['first_name']
    user.last_name = req.POST['last_name']
    user.save()
    org_group = OrgGroup(pk=req.POST['team'])
    office_location = OfficeLocation(pk=req.POST['office_location'])

    attributes = {
        'user': user,
        'stub': stub,
        'title': req.POST['title'],
        'office_location': office_location,
        'org_group': org_group,
        'office_phone': req.POST['office_phone'],
        'mobile_phone': req.POST['mobile_phone']
    }

    if req.FILES:
        attributes['photo_file'] = req.FILES['photo_file']

    person = Person(**attributes)
    person.save()
    return user
Exemplo n.º 3
0
def add_user(req):
    user = req.user
    stub = user.username.split('@')[0]
    user.email = req.POST['email']
    user.first_name = req.POST['first_name']
    user.last_name = req.POST['last_name']
    user.save()
    org_group = OrgGroup(pk=req.POST['team'])
    office_location = OfficeLocation(pk=req.POST['office_location'])

    attributes = {
        'user': user,
        'stub': stub,
        'title': req.POST['title'],
        'office_location': office_location,
        'org_group': org_group,
        'office_phone': req.POST['office_phone'],
        'mobile_phone': req.POST['mobile_phone']
    }

    if req.FILES:
        attributes['photo_file'] = req.FILES['photo_file']

    person = Person(**attributes)
    person.save()
    return user
Exemplo n.º 4
0
    def get_facebook_user(cls, client, facebook_id):
        
        """
        method to retrieve facebook user, if it doesn't exist it'll be created

        """

        try:
            fbu = cls.objects.get(facebook_id__exact=facebook_id, deleted=False)
        except cls.DoesNotExist:
            try:
                user_data = client.obj_id(
                    facebook_id,
                    fields='id,name,first_name,middle_name,last_name,link,username,gender,locale,picture',
                    )
            except FacebookGenericError:
                user_data = client.obj_id(
                    facebook_id,
                    fields='id,name,link,picture',
                    )

                person = Person(
                    name=user_data[u'name'] if u'name' in user_data else None,
                    )
                person.save()

                fbu = cls(
                    person=person,
                    facebook_id=user_data[u'id'],
                    name=user_data[u'name'] if u'name' in user_data else None,
                    link=user_data[u'link'] if u'link' in user_data else None,
                    page=True,
                    )

                if u'picture' in user_data:
                    fbu.picture = user_data[u'picture'][u'data'][u'url']
            else:
                person = Person(
                    name=user_data[u'name'] if u'name' in user_data else None,
                    gender=user_data[u'gender'] if u'gender' in user_data else None,
                    )
                person.save()

                fbu = cls(
                    person=person,
                    facebook_id=user_data[u'id'],
                    name=user_data[u'name'] if u'name' in user_data else None,
                    first_name=user_data[u'first_name'] if u'first_name' in user_data else None,
                    middle_name=user_data[u'middle_name'] if u'middle_name' in user_data else None,
                    last_name=user_data[u'last_name'] if u'last_name' in user_data else None,
                    link=user_data[u'link'] if u'link' in user_data else None,
                    username=user_data[u'username'] if u'username' in user_data else None,
                    gender=user_data[u'gender'] if u'gender' in user_data else None,
                    locale=user_data[u'locale'] if u'locale' in user_data else None,
                    picture=user_data[u'picture'][u'data'][u'url'] if u'picture' in user_data else None,
                    page=False,
                    )

            fbu.save()
        return fbu
Exemplo n.º 5
0
    def test_single_tag_multiple_users(self):
        user1 = UserF(username="******")
        person1 = Person(user=user1)
        person1.save()

        user2 = UserF(username="******")
        person2 = Person(user=user2)
        person2.save()

        tag_category = TagCategory(name='Test Category',
                                   slug='staff-directory-test-category')
        tag_category.save()

        tags = []
        tagged_item = add_tags(person1, 'TagA',
                               'staff-directory-test-category', user1,
                               'person')
        tagged_item = add_tags(person2, 'TagA',
                               'staff-directory-test-category', user1,
                               'person')
        tags.append(tagged_item.tag.slug)

        emails = _get_emails_for_tag(tags)
        self.assertTrue(len(emails) == 2)
        self.assertIn(user1.email, emails)
        self.assertIn(user2.email, emails)
Exemplo n.º 6
0
    def test_generating_slug(self):
        person = Person(name='Charles Babbage')
        person.save()

        self.assertEqual(
            person.slug,
            'charles-babbage',
        )
    def test_get_absolute_uri(self):
        person = Person(full_name='John Doe')
        person.save()

        self.assertEqual(
            person.get_absolute_url(),
            reverse('management:collaborator-detail', kwargs={'pk':
                                                              person.pk}))
Exemplo n.º 8
0
 def test_people_str(self):
     """Tests the validity of the people model"""
     with open("core/tests/test_data/person.json") as person_json:
         person = json.load(person_json)
         person_obj = Person(**person)
         person_obj.save()
         assert Person.objects.get(
             index=person['index']).name == person['name']
Exemplo n.º 9
0
    def test_generating_slug(self):
        person = Person(name='Charles Babbage')
        person.save()

        self.assertEqual(
            person.slug,
            'charles-babbage',
        )
Exemplo n.º 10
0
 def get_user(self, user, name, profile_picture):
     person = None
     try:
         person = Person.objects.get(login=user)
     except Person.DoesNotExist:
         person = Person(login=user, name=name, profile_picture=profile_picture)
         person.save()
     return person
Exemplo n.º 11
0
def create_superuser():
    user = get_user_model().objects.create_superuser('*****@*****.**', '*****@*****.**', '1')
    # If using collab, person objects needs to be created too
    if 'core' in settings.INSTALLED_APPS:
        from core.models import Person
        person = Person()
        person.user = user
        person.save()
Exemplo n.º 12
0
def create_superuser():
    user = get_user_model().objects.create_superuser('*****@*****.**',
                                                     '*****@*****.**', '1')
    # If using collab, person objects needs to be created too
    if 'core' in settings.INSTALLED_APPS:
        from core.models import Person
        person = Person()
        person.user = user
        person.save()
Exemplo n.º 13
0
	def signup(self, request, user):
		user.first_name = self.cleaned_data['first_name']	
		user.last_name = self.cleaned_data['last_name']
		user.save()
		
		person = Person()
		person.role = self.cleaned_data['cargo']
		person.user = user
		person.save()
Exemplo n.º 14
0
 def test_helper_no_profile(self):
     u = User()
     u.first_name = "John"
     u.last_name = "Smith"
     u.save()
     self.assertEquals(False, helpers.user_has_profile(u))
     p = Person()
     p.user = u
     p.save()
     self.assertEquals(True, helpers.user_has_profile(u))
Exemplo n.º 15
0
 def test_helper_no_profile(self):
     u = get_user_model()()
     u.first_name = "John"
     u.last_name = "Smith"
     u.save()
     self.assertEquals(False, helpers.user_has_profile(u))
     p = Person()
     p.user = u
     p.save()
     self.assertEquals(True, helpers.user_has_profile(u))
Exemplo n.º 16
0
 def get_user(self, user, name, profile_picture):
     person = None
     try:
         person = Person.objects.get(login=user)
     except Person.DoesNotExist:
         person = Person(login=user,
                         name=name,
                         profile_picture=profile_picture)
         person.save()
     return person
Exemplo n.º 17
0
    def handle(self, *args, **options):
        last_names = [
            'Sherman', 'Maddox', 'Montgomery', 'Small', 'Larsen', 'Marsh', 'Gardner', 'White', 'Gill', 'Pennington', 'Stein', 'Kirby', 'Jennings', 'French', 'Glass', 'Velasquez', 'Doyle', 'York', 'Fisher', 'Strong', 'Henson', 'Harmon', 'Higgins', 'James', 'Hancock', 'Drake', 'Eaton', 'Gordon', 'Harrington', 'Blevins', 'Avila', 'Solis', 'Richmond', 'Stark', 'Haynes', 'Durham', 'Montoya', 'Barrett', 'Chase', 'Mckay', 'Little', 'Perry', 'Howard', 'Caldwell', 'West', 'Fox', 'Long', 'Wright', 'Foster', 'Sloan', 'Frazier', 'Lowe', 'Cabrera', 'Barron', 'Ayala', 'Frank', 'Hammond', 'Orr', 'Holloway', 'King', 'Rush', 'Wiley', 'Neal', 'Davis', 'Fulton', 'Webb', 'Sanchez', 'Strickland', 'Clark', 'Middleton', 'Moody', 'Owens', 'Graham', 'Cotton', 'Shaffer', 'Hawkins',
            'Cooper', 'Justice', 'Clarke', 'Mcconnell', 'Mccarthy', 'Macdonald', 'Castillo', 'Gilbert', 'Horton', 'Finley', 'Beard', 'Sanders', 'Levy', 'Richard', 'Bowen', 'Grant', 'Wilkins', 'Ramsey', 'Lynch', 'Koch', 'Mercado', 'Roach', 'Bond', 'Lane', 'Tanner', 'Byers', 'Humphrey', 'Austin', 'Carney', 'Golden', 'Pope', 'Kramer', 'Ellison', 'Jefferson', 'Duffy', 'Gross', 'Mcmahon', 'Hudson', 'Mckee', 'Atkinson', 'Bush', 'Thompson', 'Faulkner', 'Christian', 'Ingram', 'Cannon', 'Gay', 'Nieves', 'Hodges', 'Langley', 'Watson', 'Woods', 'Gallagher', 'Delacruz', 'Stafford', 'Knight', 'Kerr', 'Chapman', 'Roman', 'Christensen', 'Robles', 'Mathews', 'Waller', 'Buckley', 'Myers', 'Powers', 'Lindsay', 'Gates', 'Miller', 'Johns', 'Morin', 'Fleming', 'Bishop', 'Clements']
        first_names = [
            'Sarah', 'Ian', 'Upton', 'Uriah', 'Hayden', 'Zia', 'Lila', 'Benjamin', 'Addison', 'Vivian', 'Kirby', 'Oscar', 'Demetrius', 'Hashim', 'Michelle', 'Odessa', 'Phillip', 'Michael', 'Dante', 'Omar', 'Dominic', 'Wing', 'Joshua', 'Charlotte', 'Thomas', 'Aquila', 'Rana', 'Jolene', 'Felix', 'Cailin', 'Tatiana', 'Oprah', 'Belle', 'Sydnee', 'Kuame', 'Fleur', 'Matthew', 'Sylvia', 'Mary', 'Deborah', 'Ross', 'Hyacinth', 'Jacqueline', 'Jessica', 'Callie', 'Ariana', 'Leo', 'Desiree', 'Lunea', 'Chava', 'Jorden', 'Rudyard', 'Cally', 'Knox', 'Arthur', 'Dana', 'Rebekah', 'Yen', 'Hadassah', 'Duncan', 'Ginger', 'Valentine', 'Ivana', 'Iona', 'Jemima', 'Dorothy', 'Joan', 'Timothy', 'Amity', 'Uriel', 'Skyler', 'Phelan', 'Alma', 'Hadley',
            'Quemby', 'Sonya', 'Axel', 'Slade', 'Riley', 'Rajah', 'Giselle', 'Selma', 'Nadine', 'Pascale', 'Carol', 'Steel', 'Lane', 'Emi', 'Trevor', 'Wyatt', 'Claire', 'Harlan', 'Liberty', 'Alexandra', 'Avram', 'Barbara', 'Rashad', 'Holmes', 'Kenneth', 'Preston', 'Patience', 'Adele', 'Alfonso', 'Harrison', 'Julian', 'Jena', 'Peter', 'Kessie', 'Katell', 'Denton', 'Piper', 'Jerry', 'Teegan', 'Chandler', 'Walter', 'Cheryl', 'Desirae', 'Tasha', 'Hunter', 'Logan', 'Tatyana', 'Gail', 'Galvin', 'Dara', 'Athena', 'Kay', 'Dustin', 'Faith', 'Mariam', 'Leroy', 'Edan', 'Alexis', 'Nissim', 'Octavia', 'Kareem', 'Heidi', 'Aspen', 'Gregory', 'Garrison', 'Jolie', 'Gloria', 'Alec', 'Asher', 'Julie', 'Ayanna', 'Gavin', 'Germane', 'Bertha', 'Quinn', 'Tarik']

        office_location = OfficeLocation.objects.get(pk='DC123')

        for x in xrange(int(args[0])):
            while True:
                first_name = first_names[int(random.random() *
                                             len(first_names))]
                last_name = last_names[int(random.random() * len(last_names))]
                username = last_name + first_name[0]
                email = username + '@exmaple.com'
                if not get_user_model().objects.filter(username=email).exists():
                    break

            user_attr = {
                'first_name': first_name,
                'last_name': last_name,
                'is_active': True,
                'is_superuser': False,
                'date_joined': '2012-03-01T16:03:14Z',
                'password': '******',
                'is_staff': True,
                'email': email,
                'username': email
            }

            userModel = get_user_model()
            user = userModel(**user_attr)
            user.save()

            person_attr = {
                'office_location': office_location,
                'allow_tagging': True,
                'photo_file': 'avatars/default.jpg',
                'stub': username.replace('.', ''),
                'office_phone': '5555555555',
                'user': user,
                'email_notifications': False,
                'org_group': OrgGroup.objects.order_by('?')[0]
            }

            person = Person(**person_attr)
            person.save()

        self.stdout.write(
            'Successfully created %d users and persons' % int(args[0]))
Exemplo n.º 18
0
    def test_create_tags_for_person(self):
        user = UserF(username="******")
        person = Person(user=user)
        person.save()

        tag_category = TagCategory(name='Test Category',
                                   slug='staff-directory-test-category')
        tag_category.save()

        tagged_item = add_tags(person, 'TagA', 'staff-directory-test-category',
                               user, 'person')

        self.assertEqual(1, person.tags.count())
Exemplo n.º 19
0
def create_worker(data, party):
    worker = Person()
    worker.party = party
    worker.firstName = data.get('firstName')
    worker.secondName = data.get('secondName')
    worker.patronymicName = data.get('patronymicName')
    worker.birthDate = data.get('birthDate')
    worker.startDate = datetime.now()
    worker.endDate = date.max
    worker.gender = data.get('gender')
    worker.infoText = data.get('infoText')
    worker.save()
    return worker
Exemplo n.º 20
0
    def test_create_tags_for_person(self):
        user = UserF(username="******")
        person = Person(user=user)
        person.save()

        tag_category = TagCategory(name='Test Category',
                                   slug='staff-directory-test-category')
        tag_category.save()

        tagged_item = add_tags(person, 'TagA',
                                'staff-directory-test-category', user, 'person')

        self.assertEqual(1, person.tags.count())
Exemplo n.º 21
0
Arquivo: views.py Projeto: yrik/42cc
def add_person(request):

    """
    >>> from django.test import Client
    >>> from django.core.urlresolver import reverse
    >>> client = Client()

    >>> response = client.get('add_person')
    >>> response.status_code
    200

    >>> client.post('/add_person/', {'name': 'fred')
    200
    """

    items = Person.objects.all()

    if request.method == 'POST':  # If the form has been submitted...
        form = PersonForm(request.POST)  # A  form bound to the POST data
        if form.is_valid():  # All validation rules pass
            newPerson = Person(
                        name=form.cleaned_data['name'],
                        bio=form.cleaned_data['bio'],
                        contacts=form.cleaned_data['contacts'],
                        surname=form.cleaned_data['surname'],
                        birth_date=form.cleaned_data['birth_date']
                        )
            newPerson.save()

        if request.is_ajax():
            rdict = {'bad': 'false'}
            if not form.is_valid():
                rdict.update({'bad': 'true'})
                d = {}
                for e in form.errors.iteritems():
                    d.update({e[0]: unicode(e[1])})
                rdict.update({'errs': d})
            json = simplejson.dumps(rdict, ensure_ascii=False)
            return HttpResponse(json, mimetype='application/javascript')
        else:
            return HttpResponseRedirect('/')  # Redirect after POST

    else:
        form = PersonForm()  # An unbound form

    return render_to_response('add_person.html', {
        'form': form,
        'items': items,
    },
     context_instance=RequestContext(request),
    )
Exemplo n.º 22
0
 def setUp(self):
     super().setUp()
     self.client = Client(schema)
     # Populate the test collectiom with person data
     with open("core/tests/test_data/employees.json") as employee_json:
         employees = json.load(employee_json)
         for employee in employees:
             employee_obj = Person(**employee)
             employee_obj.save()
     # Populate the test collection with company data
     with open("core/tests/test_data/companies.json") as companies_json:
         companies = json.load(companies_json)
         for companies in companies:
             companies_obj = Company(**companies)
             companies_obj.save()
Exemplo n.º 23
0
    def test_single_tag_single_user(self):
        user = UserF(username="******")
        person = Person(user=user)
        person.save()

        tag_category = TagCategory(name='Test Category',
                                   slug='staff-directory-test-category')
        tag_category.save()

        tags = []
        tagged_item = add_tags(person, 'TagA', 'staff-directory-test-category',
                               user, 'person')
        tags.append(tagged_item.tag.slug)

        emails = _get_emails_for_tag(tags)
        self.assertTrue(len(emails) == 1)
        self.assertIn(user.email, emails)
Exemplo n.º 24
0
    def test_single_tag_single_user(self):
        user = UserF(username="******")
        person = Person(user=user)
        person.save()

        tag_category = TagCategory(name='Test Category',
                                   slug='staff-directory-test-category')
        tag_category.save()

        tags = []
        tagged_item = add_tags(person, 'TagA',
                                'staff-directory-test-category', user, 'person')
        tags.append(tagged_item.tag.slug)

        emails = _get_emails_for_tag(tags)
        self.assertTrue(len(emails) == 1)
        self.assertIn(user.email, emails)
Exemplo n.º 25
0
    def setUp(self):
        super().setUp()
        self.client = Client(schema)

        # Populate the test collectiom with person data
        with open("core/tests/test_data/people.json") as people_json:
            peoples = json.load(people_json)
            for people in peoples:
                people_obj = Person(**people)
                people_obj.save()

        # Populate the food collection from test data file
        with open("core/tests/test_data/food.json") as food_json:
            food_list = json.load(food_json)
            for food in food_list:
                food_obj = Food(**food)
                food_obj.save()
Exemplo n.º 26
0
    def test_single_tag_user_profile(self):
        user = UserF(username="******")
        user.set_password("x")
        user.save()
        person = Person(user=user)
        person.stub = "jack"
        person.save()
        resp1 = self.client.login(username="******", password="******")
        self.assertTrue(resp1)

        tag_category = TagCategory(name='Test Category',
                                   slug='staff-directory-test-category')
        tag_category.save()

        resp2 = self.client.post('/staff/add-person-to-tag/%s/hello!/' %
                                (person.stub), {'person_stub': person.stub,
                                                'tag_category': 'staff-directory-test-category'})

        self.assertContains(resp2, "redirect", status_code=200)
Exemplo n.º 27
0
    def test_single_tag_user_profile(self):
        user = UserF(username="******")
        user.set_password("x")
        user.save()
        person = Person(user=user)
        person.stub = "jack"
        person.save()
        resp1 = self.client.login(username="******", password="******")
        self.assertTrue(resp1)

        tag_category = TagCategory(name='Test Category',
                                   slug='staff-directory-test-category')
        tag_category.save()

        resp2 = self.client.post(
            '/staff/add-person-to-tag/%s/hello!/' % (person.stub), {
                'person_stub': person.stub,
                'tag_category': 'staff-directory-test-category'
            })

        self.assertContains(resp2, "redirect", status_code=200)
Exemplo n.º 28
0
    def test_multiple_tags_multiple_users(self):
        user1 = UserF(username="******")
        person1 = Person(user=user1)
        person1.save()

        user2 = UserF(username="******")
        person2 = Person(user=user2)
        person2.save()

        user3 = UserF(username="******")
        person3 = Person(user=user3)
        person3.save()

        tag_category = TagCategory(name='Test Category',
                                   slug='staff-directory-test-category')
        tag_category.save()

        tags = []
        tagged_item = add_tags(person1, 'TagA',
                                'staff-directory-test-category', user1, 'person')
        tagged_item = add_tags(person2, 'TagA',
                                'staff-directory-test-category', user1, 'person')
        tags.append(tagged_item.tag.slug)

        tagged_item = add_tags(person2, 'TagB',
                                'staff-directory-test-category', user1, 'person')
        tagged_item = add_tags(person3, 'TagB',
                                'staff-directory-test-category', user2, 'person')
        tags.append(tagged_item.tag.slug)

        emails = _get_emails_for_tag(tags)
        self.assertTrue(len(emails) == 1)
        self.assertIn(user2.email, emails)
Exemplo n.º 29
0
    def test_no_emails(self):
        user1 = UserF(username="******")
        person1 = Person(user=user1)
        person1.save()

        user2 = UserF(username="******")
        person2 = Person(user=user2)
        person2.save()

        tag_category = TagCategory(name='Test Category',
                                   slug='staff-directory-test-category')
        tag_category.save()

        tags = []
        tagged_item = add_tags(person1, 'TagA',
                                'staff-directory-test-category', user1, 'person')
        tags.append(tagged_item.tag.slug)

        tagged_item = add_tags(person2, 'TagB',
                                'staff-directory-test-category', user1, 'person')
        tags.append(tagged_item.tag.slug)

        emails = _get_emails_for_tag(tags)
        self.assertEqual(len(emails), 0)
Exemplo n.º 30
0
 def handle(self, *args, **kwargs):
     for first_name in self.first_names:
         for last_name in self.last_names:
             person = Person(first_name=first_name, last_name=last_name)
             person.save()
     for producer_name in self.producer_names:
         prod = Producer(address=choice(self.street_names) + ' ' +
                         str(randint(1, 200)) + '-' + str(randint(1, 500)),
                         name=producer_name)
         prod.save()
     for taste in self.tastes:
         liquid = Liquid(producer=choice(Producer.objects.all()),
                         price=Decimal(randrange(10, 100) / 10),
                         taste=taste)
         liquid.save()
     for _ in range(100):
         tab = Tab(producer=choice(Producer.objects.all()),
                   price=Decimal(randrange(20, 300) / 10),
                   power=randint(50, 300))
         tab.save()
     for _ in range(70):
         evaporator = Evaporator(producer=choice(Producer.objects.all()),
                                 price=Decimal(randrange(50, 600) / 10))
         evaporator.save()
Exemplo n.º 31
0
from core.models import Person
from core.serializers import PersonSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

person = Person(first_name='Paul', last_name='Van Dyke',
                email='*****@*****.**')
person.save()

person = Person(first_name='Regis', last_name='Santos',
                email='*****@*****.**')
person.save()

serializer = PersonSerializer(person)
serializer.data

content = JSONRenderer().render(serializer.data)
content
Exemplo n.º 32
0
    def respond_with_new_user(self, request, next_url, desuprofile):
        User = get_user_model()
        password = create_temporary_password()

        # Kompassi has stricter rules for username validation than Desusite
        username = desuprofile.username.lower()
        try:
            valid_username(username)
        except DjangoValidationError:
            username = None

        with transaction.atomic():
            try:
                User.objects.get(username=username)
            except User.DoesNotExist:
                # Username is free
                pass
            else:
                # Username clash with an existing account, use safe username
                username = None

            if username is None:
                username = "******".format(id=desuprofile.id)

            user = User(
                username=username,
                is_active=True,
                is_staff=False,
                is_superuser=False,
            )

            user.set_password(password)
            user.save()

            person = Person(
                first_name=desuprofile.first_name,
                surname=desuprofile.last_name,
                nick=desuprofile.nickname,
                email=desuprofile.email,
                phone=desuprofile.phone,
                birth_date=datetime.strptime(desuprofile.birth_date, '%Y-%m-%d').date() if desuprofile.birth_date else None,
                notes=u'Luotu Desuprofiilista',
                user=user,
            )

            person.save()

            connection = Connection(
                id=int(desuprofile.id),
                desuprofile_username=desuprofile.username,
                user=user,
            )
            connection.save()

        person.setup_email_verification(request)

        if 'ipa_integration' in settings.INSTALLED_APPS:
            from ipa_integration.utils import create_user
            create_user(user, password)

        messages.success(request, u'Sinulle on luotu Desuprofiiliisi liitetty Kompassi-tunnus. Tervetuloa Kompassiin!')

        return respond_with_connection(request, next_url, connection)
Exemplo n.º 33
0
    def respond_with_new_user(self, request, next_url, desuprofile):
        """
        This implements the following case:

        2. No Kompassi account is linked to this Desuprofile, and no Kompassi account matches the
           Desuprofile by email address. A new Kompassi account is created and logged in.
        """

        User = get_user_model()
        password = create_temporary_password()

        # Kompassi has stricter rules for username validation than Desusite
        username = desuprofile.username.lower()
        try:
            valid_username(username)
        except DjangoValidationError:
            username = None
        else:
            try:
                User.objects.get(username=username)
            except User.DoesNotExist:
                # Username is free
                pass
            else:
                # Username clash with an existing account, use safe username
                username = None

        if username is None:
            username = "******".format(id=desuprofile.id)

        with transaction.atomic():
            user = User(
                username=username,
                is_active=True,
                is_staff=False,
                is_superuser=False,
            )

            user.set_password(password)
            user.save()

            person = Person(
                first_name=desuprofile.first_name.strip(),
                surname=desuprofile.last_name.strip(),
                nick=desuprofile.nickname.strip(),
                email=desuprofile.email.strip(),
                phone=desuprofile.phone.strip(),
                birth_date=(
                    datetime.strptime(desuprofile.birth_date.strip(), '%Y-%m-%d').date()
                    if desuprofile.birth_date
                    else None
                ),
                notes='Luotu Desuprofiilista',
                user=user,
            )

            person.save()

            connection = Connection(
                id=int(desuprofile.id),
                desuprofile_username=desuprofile.username,
                user=user,
            )
            connection.save()

        person.apply_state_new_user(request, password)
        messages.success(request, 'Sinulle on luotu Desuprofiiliisi liitetty Kompassi-tunnus. Tervetuloa Kompassiin!')

        return respond_with_connection(request, next_url, connection)
Exemplo n.º 34
0
    def respond_with_new_user(self, request, next_url, desuprofile):
        """
        This implements the following case:

        2. No Kompassi account is linked to this Desuprofile, and no Kompassi account matches the
           Desuprofile by email address. A new Kompassi account is created and logged in.
        """

        User = get_user_model()
        password = create_temporary_password()

        # Kompassi has stricter rules for username validation than Desusite
        username = desuprofile.username.lower()
        try:
            valid_username(username)
        except DjangoValidationError:
            username = None
        else:
            try:
                User.objects.get(username=username)
            except User.DoesNotExist:
                # Username is free
                pass
            else:
                # Username clash with an existing account, use safe username
                username = None

        if username is None:
            username = "******".format(id=desuprofile.id)

        with transaction.atomic():
            user = User(
                username=username,
                is_active=True,
                is_staff=False,
                is_superuser=False,
            )

            user.set_password(password)
            user.save()

            person = Person(
                first_name=desuprofile.first_name.strip(),
                surname=desuprofile.last_name.strip(),
                nick=desuprofile.nickname.strip(),
                email=desuprofile.email.strip(),
                phone=desuprofile.phone.strip(),
                birth_date=(
                    datetime.strptime(desuprofile.birth_date.strip(), '%Y-%m-%d').date()
                    if desuprofile.birth_date
                    else None
                ),
                notes='Luotu Desuprofiilista',
                user=user,
            )

            person.save()

            connection = Connection(
                id=int(desuprofile.id),
                desuprofile_username=desuprofile.username,
                user=user,
            )
            connection.save()

        person.apply_state_new_user(request, password)
        messages.success(request, 'Sinulle on luotu Desuprofiiliisi liitetty Kompassi-tunnus. Tervetuloa Kompassiin!')

        return respond_with_connection(request, next_url, connection)
Exemplo n.º 35
0
    def handle(self, *args, **options):
        last_names = [
            'Sherman', 'Maddox', 'Montgomery', 'Small', 'Larsen', 'Marsh',
            'Gardner', 'White', 'Gill', 'Pennington', 'Stein', 'Kirby',
            'Jennings', 'French', 'Glass', 'Velasquez', 'Doyle', 'York',
            'Fisher', 'Strong', 'Henson', 'Harmon', 'Higgins', 'James',
            'Hancock', 'Drake', 'Eaton', 'Gordon', 'Harrington', 'Blevins',
            'Avila', 'Solis', 'Richmond', 'Stark', 'Haynes', 'Durham',
            'Montoya', 'Barrett', 'Chase', 'Mckay', 'Little', 'Perry',
            'Howard', 'Caldwell', 'West', 'Fox', 'Long', 'Wright', 'Foster',
            'Sloan', 'Frazier', 'Lowe', 'Cabrera', 'Barron', 'Ayala', 'Frank',
            'Hammond', 'Orr', 'Holloway', 'King', 'Rush', 'Wiley', 'Neal',
            'Davis', 'Fulton', 'Webb', 'Sanchez', 'Strickland', 'Clark',
            'Middleton', 'Moody', 'Owens', 'Graham', 'Cotton', 'Shaffer',
            'Hawkins', 'Cooper', 'Justice', 'Clarke', 'Mcconnell', 'Mccarthy',
            'Macdonald', 'Castillo', 'Gilbert', 'Horton', 'Finley', 'Beard',
            'Sanders', 'Levy', 'Richard', 'Bowen', 'Grant', 'Wilkins',
            'Ramsey', 'Lynch', 'Koch', 'Mercado', 'Roach', 'Bond', 'Lane',
            'Tanner', 'Byers', 'Humphrey', 'Austin', 'Carney', 'Golden',
            'Pope', 'Kramer', 'Ellison', 'Jefferson', 'Duffy', 'Gross',
            'Mcmahon', 'Hudson', 'Mckee', 'Atkinson', 'Bush', 'Thompson',
            'Faulkner', 'Christian', 'Ingram', 'Cannon', 'Gay', 'Nieves',
            'Hodges', 'Langley', 'Watson', 'Woods', 'Gallagher', 'Delacruz',
            'Stafford', 'Knight', 'Kerr', 'Chapman', 'Roman', 'Christensen',
            'Robles', 'Mathews', 'Waller', 'Buckley', 'Myers', 'Powers',
            'Lindsay', 'Gates', 'Miller', 'Johns', 'Morin', 'Fleming',
            'Bishop', 'Clements'
        ]
        first_names = [
            'Sarah', 'Ian', 'Upton', 'Uriah', 'Hayden', 'Zia', 'Lila',
            'Benjamin', 'Addison', 'Vivian', 'Kirby', 'Oscar', 'Demetrius',
            'Hashim', 'Michelle', 'Odessa', 'Phillip', 'Michael', 'Dante',
            'Omar', 'Dominic', 'Wing', 'Joshua', 'Charlotte', 'Thomas',
            'Aquila', 'Rana', 'Jolene', 'Felix', 'Cailin', 'Tatiana', 'Oprah',
            'Belle', 'Sydnee', 'Kuame', 'Fleur', 'Matthew', 'Sylvia', 'Mary',
            'Deborah', 'Ross', 'Hyacinth', 'Jacqueline', 'Jessica', 'Callie',
            'Ariana', 'Leo', 'Desiree', 'Lunea', 'Chava', 'Jorden', 'Rudyard',
            'Cally', 'Knox', 'Arthur', 'Dana', 'Rebekah', 'Yen', 'Hadassah',
            'Duncan', 'Ginger', 'Valentine', 'Ivana', 'Iona', 'Jemima',
            'Dorothy', 'Joan', 'Timothy', 'Amity', 'Uriel', 'Skyler', 'Phelan',
            'Alma', 'Hadley', 'Quemby', 'Sonya', 'Axel', 'Slade', 'Riley',
            'Rajah', 'Giselle', 'Selma', 'Nadine', 'Pascale', 'Carol', 'Steel',
            'Lane', 'Emi', 'Trevor', 'Wyatt', 'Claire', 'Harlan', 'Liberty',
            'Alexandra', 'Avram', 'Barbara', 'Rashad', 'Holmes', 'Kenneth',
            'Preston', 'Patience', 'Adele', 'Alfonso', 'Harrison', 'Julian',
            'Jena', 'Peter', 'Kessie', 'Katell', 'Denton', 'Piper', 'Jerry',
            'Teegan', 'Chandler', 'Walter', 'Cheryl', 'Desirae', 'Tasha',
            'Hunter', 'Logan', 'Tatyana', 'Gail', 'Galvin', 'Dara', 'Athena',
            'Kay', 'Dustin', 'Faith', 'Mariam', 'Leroy', 'Edan', 'Alexis',
            'Nissim', 'Octavia', 'Kareem', 'Heidi', 'Aspen', 'Gregory',
            'Garrison', 'Jolie', 'Gloria', 'Alec', 'Asher', 'Julie', 'Ayanna',
            'Gavin', 'Germane', 'Bertha', 'Quinn', 'Tarik'
        ]

        office_location = OfficeLocation.objects.get(pk='DC123')

        for x in xrange(int(args[0])):
            while True:
                first_name = first_names[int(random.random() *
                                             len(first_names))]
                last_name = last_names[int(random.random() * len(last_names))]
                username = last_name + first_name[0]
                email = username + '@exmaple.com'
                if not get_user_model().objects.filter(
                        username=email).exists():
                    break

            user_attr = {
                'first_name': first_name,
                'last_name': last_name,
                'is_active': True,
                'is_superuser': False,
                'date_joined': '2012-03-01T16:03:14Z',
                'password':
                '******',
                'is_staff': True,
                'email': email,
                'username': email
            }

            user = get_user_model(**user_attr)
            user.save()

            person_attr = {
                'office_location': office_location,
                'allow_tagging': True,
                'photo_file': 'avatars/default1.jpg',
                'stub': username.replace('.', ''),
                'office_phone': '5555555555',
                'user': user,
                'email_notifications': False,
                'org_group': OrgGroup.objects.order_by('?')[0]
            }

            person = Person(**person_attr)
            person.save()

        self.stdout.write('Successfully created %d users and persons' %
                          int(args[0]))
Exemplo n.º 36
0
from core.models import Person
from core.serializers import PersonSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

person = Person(first_name='Paul',
                last_name='Van Dyke',
                email='*****@*****.**')
person.save()

person = Person(first_name='Regis',
                last_name='Santos',
                email='*****@*****.**')
person.save()

serializer = PersonSerializer(person)
serializer.data

content = JSONRenderer().render(serializer.data)
content
Exemplo n.º 37
0
    def handle(self, *args, **options):
        print "Pulling"
        for s in self.STATES:
            resp = urllib2.urlopen(self.URL % s).read()
            soup = BeautifulSoup(resp)
            entries = soup.findAll('p', {'align' : 'center'})
            for e in entries:
                raw = str(e)
                content = e.text.lower()


                person = Person()

                beer = re.search('(?<=beer type:).*?(?=<)', raw, re.IGNORECASE+re.DOTALL)
                if beer:
                    person.beer = beer.group(0)

                name = re.search('[a-z ]+?(?=<)', raw, re.IGNORECASE)
                if name:
                    person.name = name.group(0)
                email = e.findAll('a')
                if email:
                    person.email = email[0]['href'].replace('mailto:', '')

                if 'emergency' in content:
                    person.ok_contact = 0

                phone = re.search('(?<=phone:)[ 0-9-]{7,14}', content)
                if phone:
                    person.phone = phone.group(0).strip()


                #Location stuff
                loc = ''
                location = re.search('(?<=crossroads:).*?(?=<)', raw, re.DOTALL+re.IGNORECASE)
                if location:
                    location = location.group(0)
                    location = location.replace('&nbsp;', '')
                    location = location.replace('&amp;', ' and ')
                    loc += location
                zipcode = re.search('[0-9]{5}', raw)
                if zipcode:
                    loc += ' ' + zipcode.group(0)
                loc = loc.strip()
                if len(loc) > 4:
                    loc += ' ' + s + ', USA'
                    url = 'https://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false' % loc
                    geocode = urllib2.urlopen(urllib.quote(url, safe="%/:=&?~#+!$,;'@()*[]")).read()
                    data = json.loads(geocode)
                    if data.get('results', False) and data['results'][0].get('geometry', False):
                        lat = data['results'][0]['geometry']['location']['lat']
                        lng = data['results'][0]['geometry']['location']['lng']
                        address = data['results'][0]['formatted_address']
                        person.lat = lat
                        person.lng = lng
                        person.address = address
                    if person.lat != 0 and person.lng != 0 and len(person.phone) > 6:
                        try:
                            Person.objects.get(lat = lat, lng = lng)
                            print "Skipping %s" % person.name
                        except Person.DoesNotExist:
                            print "Saving %s" % person.name
                            print "PHONE %s" % person.phone
                            print "EMAIL %s" % person.email
                            person.save()
                            services = re.search('(?<=services:).*?(?=camping:)', raw, re.DOTALL+re.IGNORECASE)
                            if services:
                                services = services.group(0)
                                services = services.split('<br />')
                                for s in services:
                                    service = re.search('[A-Za-z -&]+', s)
                                    if service and len(service.group(0)):
                                        name = service.group(0)
                                        try:
                                            srv = Service.objects.get(name__iexact = self.first_letter_caps(name))
                                            person.services.add(srv)
                                        except Service.DoesNotExist:
                                            ns = Service(name = self.first_letter_caps(name))
                                            ns.save()
                                            person.services.add(ns)

                            person.save()
Exemplo n.º 38
0
def fill_db():
    user = User()
    user.username = '******'
    user.save()
    person = Person()
    person.user = user
    person.inn = '1'
    person.account = '1'
    person.save()

    user = User()
    user.username = '******'
    user.save()
    person = Person()
    person.user = user
    person.inn = '2'
    person.account = '0'
    person.save()

    user = User()
    user.username = '******'
    user.save()
    person = Person()
    person.user = user
    person.inn = '123'
    person.account = '50'
    person.save()

    user = User()
    user.username = '******'
    user.save()
    person = Person()
    person.user = user
    person.inn = '456'
    person.account = '50'
    person.save()

    user = User()
    user.username = '******'
    user.save()
    person = Person()
    person.user = user
    person.inn = '452345134234'
    person.account = '-100'
    person.save()

    user = User()
    user.username = '******'
    user.save()
    person = Person()
    person.user = user
    person.inn = '67896'
    person.account = '0.99'
    person.save()
Exemplo n.º 39
0
 def test_person(self):
     person = Person(name="name", surname="sur", bio="bio")
     person.save()
     self.assertEqual(person.name, "name")
     self.assertEqual(person.surname, "sur")
     self.assertEqual(person.bio, "bio")
Exemplo n.º 40
0
    def handle(self, *args, **options):
        peklun = User.objects.get(username="******")

        wks = get_spreadsheet().sheet1

        for i, l in enumerate(wks.get_all_records()):
            # reopen it time from time to avoid disconnect by timeout
            if i % 2000 == 0 and i:
                wks = get_spreadsheet().sheet1

            self.stdout.write('Processing line #{}'.format(i))

            company_ipn = l.get("ІПН", "")
            company_name = l.get("Назва", "")
            person_id = l.get("id персони", "")
            company_id = l.get("id компанії", "")
            photo_url = l.get("Фото", "")

            person = None
            # First let's search for appropriate company
            company = self.process_company(company_id, company_ipn,
                                           company_name)

            # No company — no go
            if company is None:
                continue

            # Let's backwrite company id to the spreadsheet for further use
            if company.pk != company_id:
                company_id = company.pk
                wks.update_cell(i + 2, len(l.keys()), company.pk)

            person_name = l.get("ПІБ", "").strip()
            position = l.get("Посада", "").strip()
            person_dob = unicode(l.get("Дата народження", "")).strip()
            person_from = parse_date(l.get("Дата призначення", ""))
            person_to = parse_date(l.get("Дата звільнення", ""))

            doc_received = parse_date(l.get("Дата відповіді", ""))
            docs = l.get("Лінк на відповідь", "").strip()
            website = l.get("лінк на сайт", "").strip()

            # Now let's search for the person
            if person_name:
                last_name, first_name, patronymic, _ = parse_fullname(
                    person_name)

                if not last_name:
                    continue

                # First we search by person_id (if it's present)
                if person_id:
                    try:
                        person = Person.objects.get(pk=person_id)
                    except Person.DoesNotExist:
                        pass

                # If nothing is found we search for name (for now)
                if not person:
                    try:
                        person = Person.objects.get(
                            first_name_uk__iexact=first_name,
                            last_name_uk__iexact=last_name,
                            patronymic_uk__iexact=patronymic)
                    except Person.MultipleObjectsReturned:
                        self.stderr.write(
                            "Double person {}!".format(person_name))
                    except Person.DoesNotExist:
                        pass

                # If nothing is found, let's create a record for that person
                if not person:
                    person = Person()
                    self.stderr.write(
                        "Created new person {}".format(person_name))

                person.first_name_uk = first_name
                person.last_name_uk = last_name
                person.patronymic_uk = patronymic

                Ua2RuDictionary.objects.get_or_create(term=first_name)
                Ua2RuDictionary.objects.get_or_create(term=last_name)
                Ua2RuDictionary.objects.get_or_create(term=patronymic)

                person.first_name_en = translitua(first_name)
                person.last_name_en = translitua(last_name)
                person.patronymic_en = translitua(patronymic)

                person.is_pep = True
                person.imported = True
                person.type_of_official = 1

                # Parsing date (can be a full date or just a year or
                # year/month)
                if person_dob:
                    person.dob = parse_date(person_dob)
                    if len(person_dob) == 4:
                        person.dob_details = 2  # Only year

                    if len(person_dob) > 4 and len(person_dob) < 7:
                        person.dob_details = 1  # month and year

                # Let's download the photo (if any)
                if not person.photo and photo_url:
                    photo_name, photo_san_name, photo_content = download(
                        photo_url, translitua(person_name))

                    if photo_name:
                        person.photo.save(photo_san_name,
                                          ContentFile(photo_content))
                    else:
                        self.stdout.write("Cannot download image %s for %s" %
                                          (photo_url, person_name))

                person.save()

                # Let's write the person id back to the table.
                if person.pk != person_id:
                    person_id = person.pk
                    wks.update_cell(i + 2, len(l.keys()) - 1, person.pk)

                # Now let's download all supporting docs
                docs_downloaded = []
                first_doc_name = False

                # There might be many of them
                for doc in docs.split(", "):
                    doc_instance = None

                    # we cannot download folders from google docs, so let's
                    # skip them

                    if doc and "folderview" not in doc \
                            and "drive/#folders" not in doc:
                        doc = expand_gdrive_download_url(doc)
                        doc_hash = sha1(doc).hexdigest()

                        # Check, if docs
                        try:
                            doc_instance = Document.objects.get(hash=doc_hash)
                        except Document.DoesNotExist:
                            self.stdout.write(
                                'Downloading file {}'.format(doc))
                            doc_name, doc_san_name, doc_content = download(doc)
                            doc_san_name = translitua(doc_san_name)

                            if doc_name:
                                doc_instance = Document(name_uk=doc_name,
                                                        uploader=peklun,
                                                        hash=doc_hash)

                                doc_instance.doc.save(doc_san_name,
                                                      ContentFile(doc_content))
                                doc_instance.save()
                            else:
                                self.stdout.write(
                                    'Cannot download file {}'.format(doc))

                        if doc_instance:
                            first_doc_name = doc_instance.name_uk
                            docs_downloaded.append(doc_instance.doc.url)

                # Now let's setup links between person and companies
                links = Person2Company.objects.filter(
                    (Q(date_established=person_from)
                     | Q(date_established=mangle_date(person_from))
                     | Q(date_established__isnull=True)),
                    (Q(date_finished=person_to)
                     | Q(date_finished=mangle_date(person_to))
                     | Q(date_finished__isnull=True)),
                    from_person=person,
                    to_company=company)

                # Delete if there are doubling links
                # including those cases when dates were imported incorrectly
                # because of parse_date
                if len(links) > 1:
                    links.delete()

                link, _ = Person2Company.objects.update_or_create(
                    from_person=person,
                    to_company=company,
                    date_established=person_from,
                    date_established_details=0,
                    date_finished=person_to,
                    date_finished_details=0)

                if not link.relationship_type:
                    link.relationship_type = position

                # And translate them
                Ua2EnDictionary.objects.get_or_create(
                    term=lookup_term(position))

                # oh, and add links to supporting docs
                all_docs = docs_downloaded + website.split(", ")
                if all_docs:
                    link.proof = ", ".join(filter(None, all_docs))

                    if first_doc_name:
                        link.proof_title = first_doc_name

                link.date_confirmed = doc_received
                link.is_employee = True

                link.save()