Пример #1
0
    def test_queryset_for_new_group_rule_for_general_tag_contains(self):
        # create a new group rule (and TagSet)
        group, group_rule = self.test_create_new_group_rule_for_general_tag_contains()

        # hand-create a few people, some of whom match, and others who don't
        ppl = self._generate_people(number=6)

        self.create_tag_for_person(person=ppl[0], tagset_name="General", tag="really cool test tag")
        self.create_tag_for_person(person=ppl[2], tagset_name="General", tag="really cool test tag")
        self.create_tag_for_person(person=ppl[4], tagset_name="General", tag="another tag")
        self.create_tag_for_person(person=ppl[5], tagset_name="Donor", tag="really cool test tag")

        # assert the queryset string is right
        self.assertEqual(group_rule.queryset_filter_string, "filter(taggeditem__tag__in=Tag.objects_by_account(self.account).filter(tagset__name='General',name__icontains='test'))")

        # get the queryset, make sure it matches a hand-created one.
        qs = group.members
    
        hand_qs = Person.objects_by_account(self.account).filter(Q(pk=ppl[0].pk) | Q(pk=ppl[2].pk) )
        self.assertEqualQuerySets(qs,hand_qs)

        # try for the other tag group
        group2, group_rule2 = self.test_create_new_group_rule_for_general_tag_contains(right_hand_term="another")
        hand_qs2 = Person.objects_by_account(self.account).filter(Q(pk=ppl[4].pk) )
        self.assertEqualQuerySets(group2.members,hand_qs2)
Пример #2
0
    def test_queryset_for_new_group_rule_for_custom_tag_is_exactly(self):
        # hand-create a few people, some of whom match, and others who don't
        ppl = self._generate_people(number=5)


        self.create_tag_for_person(person=ppl[0], tagset_name="new test tagset", tag="really cool test tag")
        self.create_tag_for_person(person=ppl[2], tagset_name="new test tagset", tag="really cool test tag")
        self.create_tag_for_person(person=ppl[4], tagset_name="new test tagset", tag="another tag")

        # create a new group rule
        group, group_rule = self.test_create_new_group_rule_for_custom_tag_is_exactly()

        # assert the queryset string is right
        self.assertEqual(group_rule.queryset_filter_string, "filter(taggeditem__tag__in=Tag.objects_by_account(self.account).filter(tagset__name='new test tagset',name__iexact='test'))")
        # get the queryset, make sure it matches a hand-created one.
        qs = group.members
    
        self.assertEqualQuerySets(qs,Person.objects_by_account(self.account).none())

        # check the contains group
        opposite_group, opposite_group_rule = self.test_create_new_group_rule_for_custom_tag_is_exactly(right_hand_term="test", operator_name="contains")
        opposite_hand_qs = Person.objects_by_account(self.account).filter(Q(pk=ppl[0].pk) | Q(pk=ppl[2].pk) )
        self.assertEqualQuerySets(opposite_group.members,opposite_hand_qs)

        # try for the other tag group
        group2, group_rule2 = self.test_create_new_group_rule_for_custom_tag_is_exactly(right_hand_term="another tag")
        hand_qs2 = Person.objects_by_account(self.account).filter(Q(pk=ppl[4].pk))
        self.assertEqualQuerySets(group2.members,hand_qs2)
Пример #3
0
 def save(self):
     m = Series.objects.create(
             title=self.title, title_fr=self.title_fr,
             title_int=self.title_int, begin_year=self.begin_year,
             end_year=self.end_year, id_imdb=self.id_imdb,
             poster=self.poster, rating=self.rating,
             votes=self.votes, plot=self.plot,
             language=self.language, alias=self.alias,
             number_of_episodes=0, number_of_seasons=0)
     m.save()
     for idx, actor in enumerate(self.persons['cast']):
         p = Person.add(actor)
         SeriesContributors.objects.create(
                 person=p, series=m, function='A', rank=idx)
     for idx, director in enumerate(self.persons['director']):
         p = Person.add(director)
         SeriesContributors.objects.create(
                 person=p, series=m, function='D', rank=idx)
     for idx, writer in enumerate(self.persons['writer']):
         p = Person.add(writer)
         p.save()
         SeriesContributors.objects.create(
                 person=p, series=m, function='W', rank=idx)
     for genre in self.genres:
         g = Genre.add(genre)
         m.genres.add(g)
     return m
Пример #4
0
    def test_queryset_for_new_group_rule_for_volunteer_status_is_inactive(self):
        from volunteers import VOLUNTEER_STATII
        # hand-create a few people, some of whom match, and others who don't
        ppl = self._generate_people()
        v = ppl[2].volunteer
        v.status = VOLUNTEER_STATII[2][0]    #inactive
        v.save()   
        v = ppl[4].volunteer   
        v.status = VOLUNTEER_STATII[3][0]   #temporarily inactive
        v.save()

        # create a new group rule
        group, group_rule = self.test_create_new_group_rule_for_volunteer_status_is_inactive()

        self.assertEqual(group_rule.queryset_filter_string, "filter(volunteer__status='inactive')")

        # get the queryset, make sure it matches a hand-created one.
        qs = group.members
        hand_qs = Person.objects_by_account(self.account).filter( Q(pk=ppl[2].pk) )

        self.assertEqualQuerySets(qs,hand_qs)

        # check the opposite
        opposite_group, opposite_group_rule = self.test_create_new_group_rule_for_volunteer_status_is_inactive(operator_name="is not")
        oppostite_hand_qs = Person.objects_by_account(self.account).filter(Q(pk=ppl[0].pk) | Q(pk=ppl[1].pk) | Q(pk=ppl[3].pk) | Q(pk=ppl[4].pk) )
        self.assertEqualQuerySets(opposite_group.members,oppostite_hand_qs)
Пример #5
0
def make_a_person(max=1):
    g, m, f = '','',''
    i = 1
    while i <= max:
        i += 1
        rg = random.randint(1,20)    
        if rg >= 3:
            g = random.choice(GIVEN_NAMES)
        elif rg == 2:
            g = random.choice(INITIALS)

        rm = random.randint(1,50)    
        if rm  == 49:
            m = random.choice(GIVEN_NAMES)
        elif rm == 50:
            m = random.choice(INITIALS)

        rf = random.randint(0,10)    
        if rf >= 1:
            f = random.choice(FAMILY_NAMES)
        
        name = ' '.join(('%s %s %s' %  (g, m, f)).split())
        if name == '':
            print('The name is empty!')
            return
        else:
            p = Person(name=name)
            p.save()
            print('Created person named %s' % p.name)
Пример #6
0
    def test_that_importing_a_spreadsheet_over_modified_fields_overwrites_them(self):
        """Test with first name, email, phone number, address two, 
           (if appropriate) donation amount, donation date, vol shift hours, and vol shift date"""

        # import a spreadsheet
        people_info = [self._person_dict(p) for p in Person.objects_by_account(self.a1)]

        # make a spreadsheet of them.
        s =self._create_a_person_spreadsheet_and_clear_the_data()

        s.do_import(fields=["first_name","last_name","email","phone_number"])

        # assert that they're back.
        people_info2 = [self._person_dict(p) for p in Person.objects_by_account(self.a1)]

        self.assertEqual(people_info, people_info2)


        # change a value.  Assert that they're not equal
        p = Person.objects_by_account(self.a1).all()[0]
        p.first_name = "foo"
        p.save()

        people_info2 = [self._person_dict(p) for p in Person.objects_by_account(self.a1)]

        self.assertNotEqual(people_info, people_info2)


        # import again.  Assert that we're back to where we started.
        s.do_import(fields=["first_name","last_name","email","phone_number"])

        # assert that they're back.
        people_info2 = [self._person_dict(p) for p in Person.objects_by_account(self.a1)]

        self.assertEqual(people_info, people_info2)
Пример #7
0
def add(request):
    name=request.GET.get('name')
    age = request.GET.get('age')
    person= Person()
    person.name=name
    person.age=age
    result= person.save()
    return HttpResponse(str(result))
Пример #8
0
    def test_get_row(self):
        s = self.created_and_imported_csv_spreadsheet()
        # assert that the get_row function returns what I thought it should
        
        p1 = Person.objects_by_account(self.a1).all()[0]
        p2 = Person.objects_by_account(self.a1).all()[2]

        self.assertEqual(s.get_row(0), self._mailing_list_row_dict(p1))
        self.assertEqual(s.get_row(2), self._mailing_list_row_dict(p2))
Пример #9
0
def add_person_via_organization_search_results(request):
    people = Person.objects_by_account(request.account).none()
    if 'q' in request.GET:
        q = request.GET['q']
        if q != "":
            qs = Person.objects_by_account(request.account).all()
            people = Person.search(q,queryset=qs,require_queryset=True, ignorable_chars=["-","(",")"])

    return {"fragments":{"new_person_search_results":render_to_string("organizations/_add_person_to_org_results.html", locals())}}
Пример #10
0
    def test_get_rows(self):
        s = self.created_and_imported_csv_spreadsheet()
        # assert that the get_rows function returns what I thought it should
        
        p1 = Person.objects_by_account(self.a1).all()[0]
        p2 = Person.objects_by_account(self.a1).all()[1]
        p3 = Person.objects_by_account(self.a1).all()[2]
        people = [p1, p2, p3]

        self.assertEqual(s.get_rows(0,3), [self._mailing_list_row_dict(p) for p in people ])
Пример #11
0
    def test_num_rows(self):
        # get a sample random spreadsheet with a number of rows I know
        s = self.created_and_imported_csv_spreadsheet()
        # assert that the num_rows function returns what I thought it should
        self.assertEqual(s.num_rows, Person.objects_by_account(self.a1).count())


        s2 = self.created_and_imported_excel_spreadsheet()
        # assert that the num_rows function returns what I thought it should
        self.assertEqual(s2.num_rows, Person.objects_by_account(self.a1).count())
Пример #12
0
def getPerson(row, fields, importrec):
    Person, created = Person.objects.get_or_create(
        firstname=Person.normalize("firstname",
                                    getfield(fields, "nom", row)),
        lastname=Person.normalize("lastname",
                                   getfield(fields, "prenom", row)),
        birthday=Person.normalize("lastname",
                                   getfield(fields, "datenaissance", row))
    )
    if created:
        Person.sourcetype = "I"
        Person.sourceid = importrec.pk
        if "prenoms" in fields:
            Person.prenoms = Person.normalize("prenoms",
                getfield(fields, "prenoms", row))
        if "uniquid" in fields:
            Person.uniquid = Person.normalize("uniquid",
                getfield(fields, "uniquid", row))
        if "email" in fields:
            Person.email = Person.normalize("email",
                getfield(fields, "email", row))
        if "mobile" in fields:
            Person.mobile = Person.normalize("mobile",
                getfield(fields, "mobile", row))
        password = User.objects.make_random_password(length=8)
        Person.initpass = password
        Person.save()
        print "Created Person ", Person
    else:
        print "Existing Person", Person
Пример #13
0
    def get_target_object_people_Person(self):
        from people.models import Person
        if self.has_sufficient_fields_for_identity:
            # find the matching row
            # print self.data
            if "first_name" in self.data and "last_name" in self.data and ( self.data["first_name"] != "" or self.data["last_name"] != ""):
                q = Person.objects_by_account(self.account).all()
                if "first_name" in self.data:
                    q = q.filter(first_name=self.data["first_name"])
                if "last_name" in self.data:
                    q = q.filter(last_name=self.data["last_name"])

                if q.count() == 1:
                    return q[0], False

            # print "first and last name were not enough"

            q = Person.objects_by_account(self.account).all()
            if "email" in self.data and self.data["email"] != "":
                q = q.filter(email=self.data["email"])
                
                if q.count() == 1:
                    return q[0], False
                elif q.count() > 1:
                    if "first_name" in self.data:
                        q = q.filter(first_name=self.data["first_name"])
                    if "last_name" in self.data:
                        q = q.filter(last_name=self.data["last_name"])
                    if q.count() == 1:
                        return q[0], False
                    elif q.count() > 1:
                        if "phone_number" in self.data:
                            q = q.filter(phone_number=self.data["phone_number"])
                        if q.count() == 1:
                            return q[0], False

            # print "email based search wasn't enough"

            q = Person.objects_by_account(self.account).all()
            if "phone_number" in self.data and self.data["phone_number"] != "":
                q = q.filter(phone_number=self.data["phone_number"])
                if q.count() == 1:
                    return q[0], False
                elif q.count() > 1:
                    if "first_name" in self.data:
                        q = q.filter(first_name=self.data["first_name"])
                    if "last_name" in self.data:
                        q = q.filter(last_name=self.data["last_name"])
                    if q.count() == 1:
                        return q[0], False
            
            # print "phone based search wasn't enough."
        return Person.raw_objects.create(account=self.account), True
Пример #14
0
def add_person(r):
    if(r.method == "GET"):
        return render(r, 'edit_person.jinja')
    elif(r.method == "POST"):
        p = Person(
            first_name=r.POST['fname'],
            last_name=r.POST['lname'],
            nickname=r.POST['nickname'],
            active=True,
            info=""
        )
        p.save()
        return redirect(people)
Пример #15
0
    def _that_importing_a_person_spreadsheet_refills_an_emptied_database(self, file_type=None, extension=None, fields=["first_name","last_name","email","phone_number"]):
        # create a bunch of people, store their info in a dict
        people_info = [self._person_dict(p) for p in Person.objects_by_account(self.a1)]

        # make a spreadsheet of them.
        s = self._create_a_person_spreadsheet_and_clear_the_data(file_type, extension)

        s.do_import(fields=fields)

        # assert that they're back.
        people_info2 = [self._person_dict(p) for p in Person.objects_by_account(self.a1)]

        self.assertEqual(people_info, people_info2)
Пример #16
0
    def handle(self, *options, **kwoptions):
        if len(options) != 1:
            raise CommandError('Must provide a file')

        with open(options[0]) as f:
            for line in f:
                line = line.strip()
                # ingore blank lines
                if line == '':
                    continue

                (last_name, first_name, email, username) = line.split(' ')

                password_chars = string.ascii_lowercase + string.digits
                password = ''.join(random.choice(password_chars)
                                   for x in range(6))

                person = Person(first_name = first_name,
                                last_name = last_name,
                                username = username,
                                email = email)
                person.set_password(password)
                person.is_staff = True
                person.is_superuser = True

                mail_text = EMAIL_TEXT % (first_name, username, password)

                send_mail('Welcome to ROSEdu People',
                          mail_text,
                          '*****@*****.**',
                          [email])

                person.save()
                print 'Invited %s %s' % (first_name, last_name)
Пример #17
0
def _link_adjudicator(request, pOriginalAdjudicatorName, pContestEvent):
    """
    Link the passed adjudicator to the contest
    """
    lAdjudicatorName = pOriginalAdjudicatorName

    if lAdjudicatorName.lower() == 'unknown':
        return

    # if it ends with a dot, remove it
    if lAdjudicatorName.endswith('.'):
        lAdjudicatorName = lAdjudicatorName[:-1]
    # if there is no space after a full stop then add one
    lAdjudicatorName = add_space_after_dot(lAdjudicatorName)
    # if there is no dot after an initial then add one
    lAdjudicatorName = add_dot_after_initial(lAdjudicatorName)
    # get rid of double spaces
    lAdjudicatorName = lAdjudicatorName.replace("  ", " ")

    lLastSpace = lAdjudicatorName.rfind(' ')
    if lLastSpace > 0:
        lAdjudicatorFirstNames = lAdjudicatorName[:lLastSpace].strip()
        lAdjudicatorSurname = lAdjudicatorName[lLastSpace:].strip()
    else:
        lAdjudicatorFirstNames = lAdjudicatorName
        lAdjudicatorSurname = lAdjudicatorName

    try:
        lPerson = Person.objects.filter(
            first_names__iexact=lAdjudicatorFirstNames,
            surname__iexact=lAdjudicatorSurname)[0]
    except IndexError:
        try:
            lPersonAlias = PersonAlias.objects.filter(
                name__iexact=lAdjudicatorName)[0]
            lPerson = lPersonAlias.person
        except IndexError:
            lPerson = Person()
            lPerson.surname = lAdjudicatorSurname
            lPerson.first_names = lAdjudicatorFirstNames
            lPerson.slug = slugify(lAdjudicatorName, instance=lPerson)
            lPerson.owner = request.user
            lPerson.lastChangedBy = request.user
            lPerson.save()
            notification(None, lPerson, 'people', 'person', 'new',
                         request.user, browser_details(request))

    lContestAdjudicator = ContestAdjudicator()
    lContestAdjudicator.contest_event = pContestEvent
    lContestAdjudicator.adjudicator_name = lPerson.name
    lContestAdjudicator.person = lPerson
    lContestAdjudicator.owner = request.user
    lContestAdjudicator.lastChangedBy = request.user
    lContestAdjudicator.save()
Пример #18
0
def create(request):
    """Render a form to create an entrepreneur."""
    
    if request.method == "POST":
        
        user_form = UserForm(request.POST)
        startup_form = StartupForm(request.POST,  request.FILES)
        
        if user_form.is_valid() and startup_form.is_valid():
            user = user_form.save()
            startup = startup_form.save()
            
            person = Person()
            entrepreneur = Entrepreneur()
            
            person.user = user
            person.save()
            
            entrepreneur.person = person
            entrepreneur.startup = startup
            entrepreneur.save()
            
            msg = _("Your user and startup has been created successfully.")
            
            return render_to_response("entrepreneurs/create.html",
                {
                "msg": msg,
                "user": user,
                },
                context_instance=RequestContext(request)
            )

        else:
            return render_to_response("entrepreneurs/create.html",
                {
                    "user_form": user_form,
                    "startup_form": startup_form,
                },
                context_instance=RequestContext(request)
            )
        
    else:
        return render_to_response("entrepreneurs/create.html",
            {
                "user_form": UserForm(),
                "startup_form": StartupForm(),
            },
            context_instance=RequestContext(request)
        )
Пример #19
0
    def test_that_importing_the_same_spreadsheet_multiple_times_is_idempotent(self):
        people_info = [self._person_dict(p) for p in Person.objects_by_account(self.a1)]

        # make a spreadsheet of them.
        s =self._create_a_person_spreadsheet_and_clear_the_data()

        s.do_import(fields=["first_name","last_name","email","phone_number"])

        # assert that they're back.
        people_info2 = [self._person_dict(p) for p in Person.objects_by_account(self.a1)]

        self.assertEqual(people_info, people_info2)

        s.do_import(fields=["first_name","last_name","email","phone_number"])
        people_info2 = [self._person_dict(p) for p in Person.objects_by_account(self.a1)]
        self.assertEqual(people_info, people_info2)
Пример #20
0
 def test_addorupdate_same(self):
     """ Testing duplicate detection """
     newone = copy.copy(self.people1)
     newone.pk = None
     newone.lastname = u"BARBIéR"
     addupdres = Person.add_or_update(newone)
     self.assertEqual(self.people1.pk, addupdres.pk)
Пример #21
0
    def test_importing_a_zip_works(self):
        fields = ["zip",]
        s = self._create_a_person_spreadsheet_and_clear_the_data()
        s.do_import(fields=fields)

        # assert that they're back without names
        assert all(p.zip != None for p in Person.objects_by_account(self.a1))
Пример #22
0
def index(request):
    today = datetime.date.today()
    people_meal_filter = PersonMeal.objects.filter(meal__date=today)
    try:
        who_wash = people_meal_filter.get(wash=True).person
    except PersonMeal.DoesNotExist:
        who_wash = None
    people_who_ate = [person.person.pk for person in people_meal_filter]
    try:
        meal = Meal.objects.get(date=today)
    except Meal.DoesNotExist:
        meal = Meal.objects.create(date=today)

    ranking = Person.ranking()
    people = Person.objects.all()

    return render(
        request,
        "index.html",
        {
            "people": people,
            "ranking": reversed(ranking),
            "min": meal.get_lowest_avg(),
            "form": AuthenticationForm,
            "today": today.strftime("%d/%m/%Y"),
            "pqc": people_who_ate,
            "who_wash": who_wash,
            "tickets": meal.ticket,
        },
    )
Пример #23
0
    def form_valid(self, form):

        with transaction.atomic():

            person = Person.create_from_form(form)
            check_creation_allowed(self.request.user,
                                   person.current_candidacies)
            change_metadata = get_change_metadata(self.request,
                                                  form.cleaned_data["source"])
            person.record_version(change_metadata)
            person.save()
            LoggedAction.objects.create(
                user=self.request.user,
                person=person,
                action_type="person-create",
                ip_address=get_client_ip(self.request),
                popit_person_new_version=change_metadata["version_id"],
                source=change_metadata["information_source"],
            )

            # Add a message to be displayed after redirect:
            messages.add_message(
                self.request,
                messages.SUCCESS,
                get_call_to_action_flash_message(person, new_person=True),
                extra_tags="safe do-something-else",
            )

        return HttpResponseRedirect(
            reverse("person-view", kwargs={"person_id": person.id}))
Пример #24
0
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()
Пример #25
0
	def test_try_to_get_just_one_success(self):
		# get the person
		person = Person.objects.get(first_name='First')
		# test whether the try to get function works
		result, message, multiples = Person.try_to_get_just_one(first_name='First')
		# check that we got the right results
		self.assertEqual(result,person)
		self.assertEqual(message,'matching Person record exists')
Пример #26
0
def group_count(request):
    group_id = request.GET['group_id']
    if group_id:
        group = get_or_404_by_account(Group, request.account, group_id)
        members = group.members
    else:
        members = Person.objects_by_account(request.account).all()
    return {"fragments":{"group_count":render_to_string("spreadsheets/_group_count.html", locals())}}
Пример #27
0
    def test_ignoring_a_column_actually_ignores_it(self):
        fields = ["first_name","last_name","email",]
        s = self._create_a_person_spreadsheet_and_clear_the_data()
        
        s.do_import(fields=fields)

        # assert that they're back without names
        assert all(p.phone_number == None for p in Person.objects_by_account(self.a1))
Пример #28
0
	def test_names_search_nick(self):
		# test that the search on each type of name works
		# start with first name
		results = Person.search(names='Nick')
		# check that we only got one result
		self.assertEqual(results.count(),1)
		# check that we got a result
		self.assertEqual(results.first().first_name,'First')
Пример #29
0
    def test_str(self):

        person = Person(first_name='Name', last_name='last name')

        self.assertEquals(
            str(person),
            'Name last name',
        )
Пример #30
0
 def test_addorupdate_married(self):
     """ Testing duplicate married detection """
     newone = copy.copy(self.people1)
     newone.pk = None
     newone.birthname = newone.lastname
     newone.lastname = u"MACHIN"
     addupdres = Person.add_or_update(newone)
     self.assertEqual(self.people1.pk, addupdres.pk)
Пример #31
0
    def getline(self, row, fields):
        person = Person(
            lastname=self.getfield(fields, "nom", row),
            firstname=self.getfield(fields, "prenom", row),
            ptype="stu"
        )
        birthday = self.getfield(fields, "datenaissance", row)
        if birthday != "":
            person.birthday = birthday
        person.normalize()

        if "prenoms" in fields:
            person.prenoms = self.getfield(fields, "prenoms", row)
        if "uniquid" in fields:
            person.uniquid = self.getfield(fields, "uniquid", row)
        person = Person.add_or_update(person, self.importation.log.log)
        print "Cleaning old groups"
        self.cleanup_groups(Person)
        print "Getting groups"
        for fname in fields:
            if fname not in KNOWN_FIELDS:
                group = self.getfield(fields, fname, row)
                if group == "":
                    continue
                self.put_people_in_group(group, fname, person)
Пример #32
0
    def upcoming_birthdays(self):
        from people.models import Person, NORMALIZED_BIRTH_YEAR
        from dashboard import NUMBER_BIRTHDAYS_OF_TO_SHOW
        import datetime
        from django.db.models import Q

        today = datetime.date.today()
        normalized_today = datetime.date(day=today.day, month=today.month, year=NORMALIZED_BIRTH_YEAR)
        normalized_end_date = normalized_today + datetime.timedelta(days=30)
        if today.month == 12 and today.day > 24:
            normalized_end_date = normalized_end_date - datetime.timedelta(years=1)
            if Person.objects_by_account(self).filter(normalized_birthday__gte=today).count() + \
               Person.objects_by_account(self).filter(normalized_birthday__lt=normalized_end_date).count() > NUMBER_BIRTHDAYS_OF_TO_SHOW-1:

                birthday_people = Person.objects_by_account(self).filter(Q(normalized_birthday__lt=normalized_end_date) | Q(normalized_birthday__gte=today)).all()
            else:
                birthday_people = Person.objects_by_account(self).filter(Q(normalized_birthday__lt=normalized_end_date) | Q(normalized_birthday__gte=today))
        else:
            if Person.objects_by_account(self).filter(normalized_birthday__lt=normalized_end_date, normalized_birthday__gte=today).count() > NUMBER_BIRTHDAYS_OF_TO_SHOW-1:
                birthday_people = Person.objects_by_account(self).filter(normalized_birthday__lt=normalized_end_date, normalized_birthday__gte=today)
            else:
                birthday_people = Person.objects_by_account(self).filter(normalized_birthday__gte=normalized_today) 
        
        if birthday_people:
            return birthday_people.all().order_by("birth_month","birth_day", "first_name", "last_name")[:NUMBER_BIRTHDAYS_OF_TO_SHOW]
        return None
Пример #33
0
 def composerarranger(self):
     """
     Return first of composer or arranger
     """  
     if self.composer:
         return self.composer
     if self.arranger:
         return self.arranger
     return Person()
Пример #34
0
    def test_delete_should_not_hard_delete(self):
        # create - this item exists already
        payload_existing = {**payload, "person": Person(pk=2)}
        instance = PersonWidgetDefinition.objects.create(**payload_existing)

        instance.delete()

        self.assertTrue(isinstance(instance, PersonWidgetDefinition))
        self.assertEqual(instance.group_widget, True)
        self.assertEqual(instance.user_widget, False)
Пример #35
0
def user(request):
	if request.POST:
		if '_save' in request.POST:
			p = Person.objects.filter(netid=request.POST['netid'])
			if (p):
				p1 = p[0];
				p1.netid = request.POST['netid']
				p1.first_name = request.POST['firstname']
				p1.last_name = request.POST['lastname']
				p1.lat = request.POST['lat-s']
				p1.lon = request.POST['lon-s']
				p1.save();
			else:
				p1 = Person(netid=request.POST['netid'], first_name=request.POST['firstname'], 
					last_name=request.POST['lastname'], lat=request.POST['lat-s'], lon=request.POST['lon-s'])
				p1.save();
			return HttpResponseRedirect('/')
		elif '_cancel' in request.POST:
			return HttpResponseRedirect('/')
Пример #36
0
def create(request):
    """Render a form to create an entrepreneur."""

    if request.method == "POST":

        user_form = UserForm(request.POST)
        startup_form = StartupForm(request.POST, request.FILES)

        if user_form.is_valid() and startup_form.is_valid():
            user = user_form.save()
            startup = startup_form.save()

            person = Person()
            entrepreneur = Entrepreneur()

            person.user = user
            person.save()

            entrepreneur.person = person
            entrepreneur.startup = startup
            entrepreneur.save()

            msg = _("Your user and startup has been created successfully.")

            return render_to_response("entrepreneurs/create.html", {
                "msg": msg,
                "user": user,
            },
                                      context_instance=RequestContext(request))

        else:
            return render_to_response("entrepreneurs/create.html", {
                "user_form": user_form,
                "startup_form": startup_form,
            },
                                      context_instance=RequestContext(request))

    else:
        return render_to_response("entrepreneurs/create.html", {
            "user_form": UserForm(),
            "startup_form": StartupForm(),
        },
                                  context_instance=RequestContext(request))
Пример #37
0
def people_person_create():
    from people.models import Person
    # 第一种 自动保存
    print(Person.objects.create(name='Zhoufeng', age=23))
    print(Person.objects.create(name='Zhoufeng', age=24))
    print(Person.objects.create(name='Zhoufeng', age=25))

    # 第二种
    p = Person(name='WZ', age=13)
    p.save()

    # 第三种
    p = Person(name='TWZ')
    p.age = 23
    p.save()
    """
Пример #38
0
    def _create_a_person_spreadsheet_and_clear_the_data(self, file_type=CSV_TYPE, extension=None,):
        
        if not extension:
            if file_type == CSV_TYPE:
                extension = "csv"
            elif file_type == EXCEL_TYPE:
                extension = "xls"

        # create a person spreadsheet
        fh = Factory.people_mailing_list_spreadsheet_file(self.a1, file_type=file_type)

        # delete all the people
        Person.objects_by_account(self.a1).all().delete()

        # assert that they're gone
        self.assertEqual(Person.objects_by_account(self.a1).count(), 0)

        # import the spreadsheet
        s = SpreadsheetAbstraction(self.a1, fh, "people", filename="test.%s" % (extension,))
        return s
Пример #39
0
    def activate(self, request, activation_key):
        """
        Given an an activation key, look up and activate the user
        account corresponding to that key (if possible).

        After successful activation, the signal
        ``registration.signals.user_activated`` will be sent, with the
        newly activated ``User`` as the keyword argument ``user`` and
        the class of this backend as the sender.
        
        """
        activated = RegistrationProfile.objects.activate_user(activation_key)
        if activated:
            signals.user_activated.send(sender=self.__class__,
                                        user=activated,
                                        request=request)
            person = Person(user=activated)
            activated.save()
            person.save()
        return activated
Пример #40
0
    def activate(self, request, activation_key):
        """
        Given an an activation key, look up and activate the user
        account corresponding to that key (if possible).

        After successful activation, the signal
        ``registration.signals.user_activated`` will be sent, with the
        newly activated ``User`` as the keyword argument ``user`` and
        the class of this backend as the sender.
        
        """
        activated = RegistrationProfile.objects.activate_user(activation_key)
        if activated:
            signals.user_activated.send(sender=self.__class__,
                                        user=activated,
                                        request=request)
            person = Person(user=activated)
            activated.save()
            person.save()
        return activated
Пример #41
0
    def test_delete_should_hard_delete(self):
        payload_existing = {**payload, "person": Person(pk=2)}
        instance = PersonWidgetDefinition.objects.get(**payload_existing)
        instance.group_widget = False
        instance.save()

        _sum, _ = instance.delete()

        self.assertEqual(_sum, 1)
        with self.assertRaises(PersonWidgetDefinition.DoesNotExist):
            PersonWidgetDefinition.objects.get(**payload_existing)
Пример #42
0
def create(request):
    """Render a form to create a mentor."""

    if request.method == "POST":

        user_form = UserForm(request.POST)
        mentor_form = MentorForm(request.POST)

        if user_form.is_valid() and mentor_form.is_valid():
            user = user_form.save()

            person = Person()
            mentor = mentor_form.save(commit=False)

            person.user = user
            person.save()

            mentor.person = person
            mentor.save()

            msg = _("Your user has been created successfully.")

            return render_to_response("mentors/create.html", {
                "msg": msg,
                "user": user,
            },
                                      context_instance=RequestContext(request))
        else:
            return render_to_response("mentors/create.html", {
                "user_form": user_form,
                "mentor_form": mentor_form,
            },
                                      context_instance=RequestContext(request))

    else:
        return render_to_response("mentors/create.html", {
            "user_form": UserForm(),
            "mentor_form": MentorForm(),
        },
                                  context_instance=RequestContext(request))
Пример #43
0
def new_person(request):
    required_method_type = "POST"
    if not check_method_type(request, required_method_type):
        return invalid_method(required_method_type)

    try:
        parsed_body = json.loads(request.body.decode('utf-8'))
    except:
        return error('no body')

    for field in Person.required_fields:
        if field not in parsed_body:
            return error('mising fields')

    if 'api_key' in parsed_body:
        admin = check_api_key(parsed_body['api_key'])
    else:
        admin = False
    if not admin:
        return error('Admin only action')

    parsed_body['hashed_password'] = bcrypt.hashpw(
        parsed_body['password'].encode('utf-8'), bcrypt.gensalt())
    try:
        del parsed_body['password']
        del parsed_body['api_key']
    except KeyError:
        return error('cant delete')

    person = Person(**parsed_body)
    try:
        person.save()
    except:
        print('ERROR: Can\'t create person.')
        print(sys.exc_info())
        return error('Can\'t create person.')

    return JsonResponse(Person.admin_view(person))
Пример #44
0
    def to_representation(self, instance):
        ret = super().to_representation(instance)

        # UI Expectation
        expectation = {
            'totalDashboards':
            Dashboard.objects.filter(user_id=ret['id']).count(),
            'totalGroups': instance.groups.filter(stack_default=False).count(),
            'totalStacks': len(Person.get_directly_assigned_stacks(instance)),
            'totalWidgets': instance.personwidgetdefinition_set.count(),
        }

        ret.update(expectation)
        return ret
Пример #45
0
    def test_get_friends(self):
        """
        Person is { 
            index: int,
            friends: [Person]
            }

        def fn_for_person(person):
            ... person['index'], 
                fn_for_lop(person['friends'])

        def fn_for_lop(people):
            if not people:
                ... 
            else:
                ... fn_for_person(people[0]), fn_for_lop(people[1:])

        ----
        json_data = data

        def fn_for_person(person):
            # Prerequisite: person must contain all raw data
            obj = cls.objects.get_or_create(
                person['index']
            )
            obj.add(*fn_for_lop(person['friends']))
            return obj

        def fn_for_lop(people):
            if not people:
                return []
            else:
                if obj = cls.objects.get('index'=people[0]['index']):
                    return [obj] + fn_for_lop(people[1:])
                else:
                    return [fn_for_person(find_person(people[0], json_data))] + fn_for_lop(people[1:])
        """
        person0 = {"index": 0, "friends": [{"index": 1}]}
        person1 = {"index": 1, "friends": [{"index": 2}, {"index": 0}]}
        person2 = {"index": 2, "friends": [{"index": 1}]}
        people = [person0, person1, person2]
        objs = Person.get_friends(person0["friends"], people)
        self.assertTrue(len(objs) > 0)
        for o in objs:
            self.assertIsInstance(o, Person)
Пример #46
0
def person(request):
    if request.method == "POST":
        if request.body:
            jsonData = json.loads(request.body.decode("utf-8"))
            if jsonData["id"]:
                client_id = bleach.clean(jsonData["id"])
                try:
                    person = Person.objects.filter(client_id=client_id)[0]
                    response = {
                        **Person.admin_view(person),
                        **{
                            'success': True
                        }
                    }
                    return JsonResponse(response, safe=False)
                except IndexError:
                    return JsonResponse({"Error": "Invalid"}, safe=False)
                except:
                    print(sys.exc_info())
                    return JsonResponse({"Error": "Invalid"}, safe=False)
Пример #47
0
def patrons(request):
    o = Organization.get()
    page_name = "patrons"
    if request.method == "GET" and "q" in request.GET:
        hashed_email = lookup_hash(request.GET["q"])
        people = Person.objects.filter(hashed_email=lookup_hash, patron=True)
    elif request.method == "POST":
        adding = True
        added = False
        new_email = request.POST["patron_email"]
        new_patron = Person.get_by_email(new_email)

        if new_patron:
            added = True
            new_patron.patron = True
            new_patron.save()

        people = Person.objects.filter(patron=True).all()
    else:
        people = Person.objects.filter(patron=True).all()
    return locals()
Пример #48
0
def authenticate(request):
    error = False
    #print(request.body.decode("utf-8"))
    if request.method == "POST":
        if request.body:
            jsonData = json.loads(request.body.decode("utf-8"))
            if jsonData["username"] and jsonData["password"]:
                username = bleach.clean(jsonData["username"])
                password = jsonData["password"]
                try:
                    person = Person.objects.filter(username=username)[0]
                    if bcrypt.checkpw(password.encode('utf-8'),
                                      bytes(person.hashed_password)):
                        response = {
                            **Person.admin_view(person),
                            **{
                                'success': True
                            }
                        }
                        return JsonResponse(response, safe=False)
                    else:
                        return JsonResponse({"Error": "Invalid Login"},
                                            safe=False)

                except IndexError:
                    return JsonResponse({"Error": "Invalid Login"}, safe=False)
                except:
                    print(sys.exc_info())
                    return JsonResponse({"Error": "Invalid Login"}, safe=False)

    instructions = {
        0: "New post must be submitted as POST request with a json body.",
        1: {
            "Required Fields:": {
                0: "username",
                1: "password"
            }
        }
    }
    return JsonResponse(instructions, safe=False)
Пример #49
0
    def deal_excel(self):
        upload_file = UploadRecord.objects.filter(upload_time=self.timestamp).first()
        file_path = upload_file.excel_file.path
        book = xlrd.open_workbook(file_path)
        for sheet in book.sheets():
            for row in sheet.get_rows():
                try:
                    p_name = row[0].value
                    p_num = row[1].value

                    if p_name == '':
                        break
                    if not str(p_num).isalnum():
                        break
                    birthday_str = p_num[6:14]
                    birthday = datetime.strptime(birthday_str, "%Y%m%d")

                    if int(p_num[16]) % 2 == 0:
                        sex = False
                    else:
                        sex = True

                except Exception as e:
                    logger.error(e)
                    upload_file.status = '解析出错误,请确认表格格式。'
                    upload_file.save()
                else:
                    Person(
                        name=p_name,
                        id_num=p_num,
                        birthday=birthday,
                        sex=sex,
                        create_time=self.timestamp
                    ).save()
        upload_file.status = '解析成功'
        upload_file.save()
Пример #50
0
def me(request):
    if request.user.is_authenticated:
        return {
            'me': Person.get_from_user(request.user)
        }
    return {}
Пример #51
0
def enter_results(request, pContestSlug, pDate):
    """
    Enter the actual results of the contest
    """
    lForm = ResultsForm()
    lHowToCorrectErrors = ''
    try:
        lContest = Contest.objects.filter(slug=pContestSlug)[0]
        lContestEvent = ContestEvent.objects.filter(contest=lContest,
                                                    date_of_event=pDate)[0]
    except IndexError:
        raise Http404()

    # if flag is set, forward to adjudicator and don't allow results to be added
    lToday = date.today()
    if lToday < lContestEvent.date_of_event and lContest.prevent_future_bands:
        return HttpResponseRedirect('/addresults/%s/%s/6/' %
                                    (pContestSlug, pDate))

    if request.POST:
        try:
            lRadioSelection = request.POST['conductor_choice']
            if lRadioSelection == 'newconductor':
                lNewConductorPerson = Person()
                lNewConductorPerson.name = request.POST['conductor']
                lNewConductorPerson.slug = slugify(
                    lNewConductorPerson.name, instance=lNewConductorPerson)
                lNewConductorPerson.lastChangedBy = request.user
                lNewConductorPerson.owner = request.user
                lNewConductorPerson.save()
                notification(None, lNewConductorPerson, 'people', 'person',
                             'new', request.user, browser_details(request))

            elif lRadioSelection == 'alias':
                lPreviousConductorName = request.POST['conductoralias']
                lConductorSerial = request.POST['conductorid']

                lConductor = Person.objects.filter(id=int(lConductorSerial))[0]
                lPreviousName = PersonAlias()
                lPreviousName.name = lPreviousConductorName
                lPreviousName.person = lConductor
                lPreviousName.lastChangedBy = request.user
                lPreviousName.owner = request.user
                lPreviousName.save()
                notification(None, lPreviousName, 'people', 'person_alias',
                             'new', request.user, browser_details(request))

                ## TODO create person alias here - we'll need to pass through the person id, not the conductor id

        except MultiValueDictKeyError:
            pass

        try:
            lRadioSelection = request.POST['band']
            if lRadioSelection == 'newband':
                # create a new band
                lNewBandName = request.POST['newbandname']
                lNewBandRegion = request.POST['newbandregion']
                lNewBand = Band()
                lNewBand.name = lNewBandName
                lNewBand.slug = slugify(lNewBandName, instance=lNewBand)
                lNewBand.region = Region.objects.filter(id=lNewBandRegion)[0]
                lNewBand.owner = request.user
                lNewBand.lastChangedBy = request.user
                lNewBand.save()
                notification(None, lNewBand, 'bands', 'band', 'new',
                             request.user, browser_details(request))
            elif lRadioSelection == 'nameonly':
                lPreviousBandName = request.POST['oldbandname']
                lBandSerial = request.POST['bandid']
                lBand = Band.objects.filter(id=int(lBandSerial))[0]
                lPreviousName = PreviousBandName()
                lPreviousName.old_name = lPreviousBandName
                lPreviousName.band = lBand
                lPreviousName.lastChangedBy = request.user
                lPreviousName.owner = request.user
                lPreviousName.save()
                notification(None, lPreviousName, 'bands', 'band_alias', 'new',
                             request.user, browser_details(request))
        except MultiValueDictKeyError:
            pass

        lForm = ResultsForm(request.POST)
        lForm.event = lContestEvent
        if lForm.is_valid():
            lForm.save(request, lContestEvent)
            return HttpResponseRedirect('/addresults/%s/%s/6/' %
                                        (pContestSlug, pDate))
        else:
            lFormErrors = str(lForm.errors['results'])
            if lFormErrors.startswith(_CONDUCTOR_PREFIX):
                lConductorName = lFormErrors[len(_CONDUCTOR_PREFIX):-15]
                lConductorDropList = '<select name="conductorid">\n'
                lConductors = Person.objects.all()
                for conductor in lConductors:
                    lAdd = True
                    if conductor.end_date and lContestEvent.date_of_event > conductor.end_date:
                        lAdd = False
                    elif conductor.start_date and lContestEvent.date_of_event < conductor.start_date:
                        lAdd = False
                    if lAdd:
                        lConductorDropList = lConductorDropList + '<option value="%s">%s, %s</option>\n' % (
                            conductor.id, conductor.surname,
                            conductor.first_names)
                lConductorDropList = lConductorDropList + '</select>'

                lHowToCorrectErrors = """<input type="radio" name="conductor_choice" value="newconductor"/>Next submit will create a new conductor called: <input type="text" name="conductor" value="%s"/><br/>
                                         <input type="radio" name="conductor_choice" value="alias"/>Next submit will add a conductor alias of <b>%s</b> to %s<input type="hidden" name="conductoralias" value="%s"/><br/>
                                         <input type="radio" name="conductor_choice" value="nothing" checked="checked"/>Do nothing, correct it in the text box below.""" % (
                    lConductorName, lConductorName, lConductorDropList,
                    lConductorName)
            if lFormErrors.startswith(_BAND_PREFIX):
                lBandName = lFormErrors[len(_BAND_PREFIX):-15]
                #lBandName = lFormErrors[len(_BAND_PREFIX):-15]
                lBandDropList = '<select name="bandid">\n'
                lBands = Band.objects.all()
                for band in lBands:
                    lAdd = True
                    if band.end_date and lContestEvent.date_of_event > band.end_date:
                        lAdd = False
                    elif band.start_date and lContestEvent.date_of_event < band.start_date:
                        lAdd = False
                    if lAdd:
                        lBandDropList = lBandDropList + '<option value="%s">%s</option>\n' % (
                            band.id, band.name)
                lBandDropList = lBandDropList + '</select>'
                lRegionDropList = ""
                lContestRegion = "Unknown"
                if lContest.region:
                    lContestRegion = lContest.region.name
                for region in Region.objects.all():
                    lRegionDropList += "<option value='" + str(region.id) + "'"
                    if region.name == lContestRegion:
                        lRegionDropList += " selected='selected'"
                    lRegionDropList += ">" + region.name + "</option>\n"
                lHowToCorrectErrors = """You have two choices to fix this problem.  You can either create a new band, or assign this name as an old name of an already existing band.  Use existing bands where possible.<br/>
                                         <input type="radio" name="band" value="newband"/>Next submit will create a new band called: <input type="text" name="newbandname" value="%s"/> in <select name="newbandregion">%s</select> region<br/>
                                         <input type="radio" name="band" value="nameonly"/>Next submit will add a previous band name to %s called <b>%s</b><input type="hidden" name="oldbandname" value="%s"/><br/>
                                         <input type="radio" name="band" value="nothing" checked="checked"/>Do nothing, correct it in the text box below.
                                         """ % (lBandName, lRegionDropList,
                                                lBandDropList, lBandName,
                                                lBandName)

    return render_auth(
        request, 'addresults/bands.html', {
            "Contest": lContest,
            "ContestEvent": lContestEvent,
            "form": lForm,
            "HowToCorrectErrors": lHowToCorrectErrors,
        })
Пример #52
0
 def person_instance(self):
     return Person(name="test person", linkedin_url="https://www.linkedin.com/in/testperson")
Пример #53
0
def enter_composer(request, pContestSlug, pDate):
    """
    Enter composer for test piece, only shown if we don't match an existing piece
    """
    try:
        lContest = Contest.objects.filter(slug=pContestSlug)[0]
        lContestEvent = ContestEvent.objects.filter(contest=lContest,
                                                    date_of_event=pDate)[0]
    except IndexError:
        raise Http404()

    if request.POST:
        lComposerName = add_space_after_dot(request.POST['Composer'])
        lLastSpace = lComposerName.rfind(' ')
        if lLastSpace > 0:
            lComposerFirstNames = lComposerName[:lLastSpace].strip()
            lComposerSurname = lComposerName[lLastSpace:].strip()
        else:
            lComposerSurname = lComposerName
            lComposerFirstNames = ''

        lArrangerName = add_space_after_dot(request.POST['Arranger'])
        lArrangerFirstNames = ''
        lArrangerSurname = ''
        if len(lArrangerName.strip()) > 0:
            lLastSpace = lArrangerName.rfind(' ')
            if lLastSpace > 0:
                lArrangerFirstNames = lArrangerName[:lLastSpace].strip()
                lArrangerSurname = lArrangerName[lLastSpace:].strip()
            else:
                lArrangerSurname = lArrangerName

        lArrangerPerson = None
        lComposerPerson = None

        lTestPiece = lContestEvent.test_piece
        if len(lComposerName.strip()) > 0:
            try:
                lComposerPerson = Person.objects.filter(
                    surname__iexact=lComposerSurname,
                    first_names__iexact=lComposerFirstNames)[0]
            except IndexError:
                try:
                    lPersonAlias = PersonAlias.objects.filter(
                        name__iexact=lComposerName)[0]
                    lArrangerPerson = lPersonAlias.person
                except IndexError:
                    lPerson = Person()
                    lPerson.surname = lComposerSurname
                    lPerson.first_names = lComposerFirstNames
                    lPerson.slug = slugify(lComposerName, instance=lPerson)
                    lPerson.owner = request.user
                    lPerson.lastChangedBy = request.user
                    lPerson.save()
                    lArrangerPerson = lPerson
                    notification(None, lPerson, 'people', 'person', 'new',
                                 request.user, browser_details(request))

        if len(lArrangerName.strip()) > 0:
            try:
                lArrangerPerson = Person.objects.filter(
                    surname__iexact=lArrangerSurname,
                    first_names__iexact=lArrangerFirstNames)[0]
            except IndexError:
                try:
                    lPersonAlias = PersonAlias.objects.filter(
                        name__iexact=lArrangerName)[0]
                    lArrangerPerson = lPersonAlias.person
                except IndexError:
                    lPerson = Person()
                    lPerson.surname = lArrangerSurname
                    lPerson.first_names = lArrangerFirstNames
                    lPerson.slug = slugify(lArrangerName, instance=lPerson)
                    lPerson.owner = request.user
                    lPerson.lastChangedBy = request.user
                    lPerson.save()
                    lArrangerPerson = lPerson
                    notification(None, lPerson, 'people', 'person', 'new',
                                 request.user, browser_details(request))

        lTestPiece.arranger = lArrangerPerson
        lTestPiece.composer = lComposerPerson
        lTestPiece.save()
        return HttpResponseRedirect('/addresults/%s/%s/4/' %
                                    (pContestSlug, pDate))
    else:
        if lContestEvent.test_piece == None or lContestEvent.test_piece.composer or lContestEvent.test_piece.arranger:
            return HttpResponseRedirect('/addresults/%s/%s/4/' %
                                        (pContestSlug, pDate))
        else:
            cursor = connection.cursor()
            lComposerNames = []
            cursor.execute(
                "select first_names || ' ' || surname || ' ' || coalesce (suffix, '') from people_person order by 1"
            )
            rows = cursor.fetchall()
            for row in rows:
                lComposerNames.append(row[0].strip())
            cursor.close()

            return render_auth(
                request, 'addresults/composer.html', {
                    "Contest": lContest,
                    "ContestEvent": lContestEvent,
                    "Data": lComposerNames,
                })
Пример #54
0
 def create(self, validated_data):
     new = Person(**validated_data)
     new.save()
     return new
Пример #55
0
    'name': 'test stack 3',
    'description': 'test description 3'
}

create_stack_payload4 = {
    'name': 'test stack 4',
    'description': 'test description 4'
}

create_stack_payload5 = {
    'name': 'test stack 5',
    'description': 'test description 5'
}

payload = {
    "person": Person(pk=2),
    "widget_definition": WidgetDefinition(pk=1),
}

payload = {
    "person": Person(pk=2),
    "widget_definition": WidgetDefinition(pk=16),
}


class PersonModelTests(TestCase):
    fixtures = ['resources/fixtures/default_data.json', ]

    def setUp(self):
        # create user - done by fixture for now
        self.admin_user = Person.objects.get(pk=1)
Пример #56
0
 def test_get_stacks_for_user(self):
     stacks = len(Person.get_directly_assigned_stacks(self.admin_user))
     self.assertGreaterEqual(stacks, 2)
Пример #57
0
    def dispatch(self, request, *args, **kwargs):
        response = super().dispatch(request, *args, **kwargs)
        if Person.get_from_user(request.user) is None and request.user.is_authenticated:
            return redirect('people:setup')

        return response
Пример #58
0
def execute_upoad(file, user_id, block_id):
    global ERROR

    user_id = CocoUser.objects.get(user__id=user_id)
    block_id = Block.objects.get(id=block_id)

    file_name = str(os.path.splitext(file)[0])
    file_name_list = str(os.path.splitext(file)[0].split('/')[-1])

    village_errors_file = open(file_name + '_errors_village.csv', 'wb')
    wrtr = csv.writer(village_errors_file, delimiter=',', quotechar='"')
    wrtr.writerow(["Entry No.", "Village Name", "Error"])

    village_success_file = open(file_name + '_success_village.csv', 'wb')
    wrtr_success = csv.writer(village_success_file, delimiter=',', quotechar='"')
    wrtr_success.writerow(["Entry No.", "Village Name"])

    csvfile = open(file, 'rb')
    rows_villages = csv.DictReader(csvfile)

    village_querry_set = Village.objects.values_list('village_name','id').filter(block_id=block_id.id)
    village_map = dict(village_querry_set)
    i = 0
    for row in rows_villages:
        if unicode(row['Village_Name']) not in village_map:
            i = i + 1
            try:
                village = Village(user_created_id=user_id.id, 
                                  village_name=unicode(row['Village_Name']),
                                  block_id=block_id.id)
                village.save()
                village_map[unicode(row['Village_Name'])] = village.id
                wrtr_success.writerow([i, unicode(row['Village_Name'])])
                village_success_file.flush()

            except Exception as e:
                ERROR += 1
                wrtr.writerow([i, unicode(row['Village_Name']), e])
                village_errors_file.flush()

    village_success_file.close()
    village_errors_file.close()

    ERROR_FILENAMES.append(file_name_list + '_errors_village.csv')
    SUCCESS_FILENAMES.append(file_name_list + '_success_village.csv')

    group_errors_file = open(file_name + '_errors_group.csv', 'wb')
    wrtr = csv.writer(group_errors_file, delimiter=',', quotechar='"')
    wrtr.writerow(["Entry No.", "Shg Name", "Error"])

    group_success_file = open(file_name + '_success_group.csv', 'wb')
    wrtr_success = csv.writer(group_success_file, delimiter=',', quotechar='"')
    wrtr_success.writerow(["Entry No.", "Shg Name"])

    csvfile = open(file, 'rb')
    rows_groups = csv.DictReader(csvfile)

    group_querry_set = PersonGroup.objects.values_list('group_name', 'id')
    group_map = dict(group_querry_set)

    i = 0
    for row in rows_groups:
        if unicode(row['Shg_Name']) + unicode(row['Village_Name']) not in group_map:
            i = i + 1
            try:
                group = PersonGroup(user_created_id=user_id.id,
                                    partner_id=user_id.partner.id,
                                    group_name=row['Shg_Name'],
                                    village_id=village_map[unicode(row['Village_Name'])])
                group.save()
                group_map[row['Shg_Name'] + unicode(row['Village_Name'])] = group.id
                wrtr_success.writerow([i, row['Shg_Name']])
                group_success_file.flush()
            except Exception as e:
                ERROR += 1
                wrtr.writerow([i, row['Shg_Name'], e] )
            group_errors_file.flush()

    group_errors_file.close()
    group_success_file.close()

    ERROR_FILENAMES.append(file_name_list + '_errors_group.csv')
    SUCCESS_FILENAMES.append(file_name_list + '_success_group.csv')

    person_errors_file = open(file_name + '_errors_person.csv', 'wb')
    wrtr = csv.writer(person_errors_file, delimiter=',', quotechar='"')
    wrtr.writerow(["Entry No.", "Person Name", "Error"])

    person_success_file = open(file_name + '_success_person.csv', 'wb')
    wrtr_success = csv.writer(person_success_file, delimiter=',', quotechar='"')
    wrtr_success.writerow(["Entry No.", "Person Name"])

    csvfile = open(file, 'rb')
    rows_persons = csv.DictReader(csvfile)

    i = 0
    for row in rows_persons:
        i = i + 1
        try:
            person_name = ' '.join([unicode(row['Member_Name']), unicode(row['Member_Surname'])])
            father_name = ' '.join([unicode(row['Husband_Father_Name']),
                                    unicode(row['Husband_Father_Surname'])])
            gender = str(row['Gender(M/F)'])
            if (row['Age'] == ''):
                age = None
            else:
                age = float(row['Age'])
   
            if (str(row['Phone_Number']) == ''):
                phone_number = str('')
            else:
                phone_number = str(row['Phone_Number'])
            
            person = Person(user_created_id=user_id.id,
                            partner_id=user_id.partner.id,
                            person_name=person_name,
                            father_name=father_name,
                            village_id=village_map[unicode(row['Village_Name'])],
                            group_id=group_map[row['Shg_Name'] + unicode(row['Village_Name'])],
                            gender=gender,
                            age = age,
                            phone_no = phone_number
                            )
            person.save()
            wrtr_success.writerow([i, person_name])
            person_success_file.flush()
        except Exception as e:
            ERROR += 1
            wrtr.writerow([i, person_name, e])
        person_errors_file.flush()

    person_errors_file.close()
    person_success_file.close()
    ERROR_FILENAMES.append(file_name_list + '_errors_person.csv')
    SUCCESS_FILENAMES.append(file_name_list + '_success_person.csv')
Пример #59
0
def testdb(request):
    person = Person(name='runoob', age=13)
    person.save()
    return HttpResponse("<p>数据添加成功!</p>")