def setUp(self): self.department = DepartmentFactory() self.activity = Activity( start_date=datetime.now(), end_date=datetime.now() + timedelta(days=365), # Has to be long enough to be a season department=self.department, ) self.activity.save() self.assertTrue( self.activity.is_season()) # If this fail increase the end_date self.family = Family(email="*****@*****.**") self.family.save() self.person = Person(family=self.family) self.person.save() self.member = Member(department=self.department, person=self.person, is_active=True) self.member.save() waitinglist = WaitingList( person=self.person, department=self.department, on_waiting_list_since=datetime.now() - timedelta(days=1), ) waitinglist.save() self.waitinglist_id = waitinglist.id
class TestModelActivityParticipant(TestCase): # ToDo: Maybe test payment def setUp(self): self.union = Union() self.union.save() self.department = Department( union=self.union ) self.department.save() self.activity = Activity( start_date=datetime.now(), end_date=datetime.now() + timedelta(days=365), # Has to be long enough to be a season department=self.department ) self.activity.save() self.assertTrue(self.activity.is_season()) # If this fail increase the end_date self.family = Family( email='*****@*****.**' ) self.family.save() self.person = Person( family=self.family ) self.person.save() self.member = Member( department=self.department, person=self.person, is_active=True ) self.member.save() waitinglist = WaitingList( person=self.person, department=self.department, on_waiting_list_since=datetime.now() - timedelta(days=1) ) waitinglist.save() self.waitinglist_id = waitinglist.id def test_save_waiting_list(self): self.participant = ActivityParticipant( activity=self.activity, member=self.member ) self.participant.save() self.assertFalse(WaitingList.objects.filter(pk=self.waitinglist_id).exists())
def fill_data(self): ''' Fills in dummy content that we will use for testing 2 members, Peter and Hans. 2 workgroups, Systems and Besteling. Peter is the only member in Systems. Both are members in Bestel, with Hans leading that one. Bestel has a shift ('do stuff') for Peter. ''' m1 = Member(fname=u'Peter', prefix=u'de', lname='Pan') m1.mem_email = '*****@*****.**' m1.mem_enc_pwd = md5_crypt.hash('notsecret') self.DBSession.add(m1) m2 = Member(fname=u'Hans', prefix=u'de', lname='Wit') m1.mem_email = '*****@*****.**' self.DBSession.add(m2) wg1 = Workgroup(name=u'Systems', desc=u'IT stuff') self.DBSession.add(wg1) wg2 = Workgroup(name=u'Besteling', desc=u'Besteling at wholesale') self.DBSession.add(wg2) self.DBSession.flush() # flush now to get member and workgroup IDs wg1.members.append(m1) wg1.leaders.append(m1) wg2.members.append(m1) wg2.members.append(m2) wg2.leaders.append(m2) self.DBSession.flush() s = Shift(wg2.id, 'do stuff', 2012, 6, member=m1) self.DBSession.add(s) self.DBSession.flush() # reserved transaction types for rt in reserved_ttype_names: self.DBSession.add(TransactionType(name=rt)) self.DBSession.flush()
def addAdmin(): ''' after old names are added, he has ID 3 ''' admin = Member(fname=u'Adalbert', lname='Adminovic') admin.mem_email = '*****@*****.**' admin.mem_mobile = "06" + unicode(random.randint(10000000, 100000000)) admin.household_size = 1 salt = md5crypt('notsecret', '') admin.mem_enc_pwd = md5crypt('notsecret', salt) admin.mem_admin = True admin.mem_active = True DBSession.add(admin) DBSession.flush() wgs = DBSession.query(Workgroup).filter( Workgroup.name == u'Systems').first() wgs.members.append(admin) wgm = DBSession.query(Workgroup).filter( Workgroup.name == u'Membership').first() wgm.members.append(admin)
def __call__(self): session = DBSession() a_id = self.request.matchdict['a_id'] applicant = get_applicant(session, a_id) # copy over our knowledge of him/her member = Member(self.request, applicant.fname, '', applicant.lname) now = datetime.now() txt = "Joined orientation in {}, became member in {}/{}.".format(\ applicant.month, now.month, now.year) member.mem_adm_comment = "{}\n{}".format(txt, applicant.comment) member.mem_email = applicant.email member.mem_home_tel = applicant.telnr member.mem_household_size = applicant.household_size member.validate() session.add(member) session.delete(applicant) session.flush() send_pwdreset_request(member, self.request.application_url, first=True) return self.redirect("/member/{}?msg=Applicant has been made "\ "into a new Member and got an email to set up a "\ "password."\ .format(member.mem_id))
def addOldNames(): m1 = Member(fname=u'Peter', prefix=u'de', lname='Pan') m1.mem_email = '*****@*****.**' m1.mem_enc_pwd = md5crypt('notsecret', 'notsecret') DBSession.add(m1) m2 = Member(fname=u'Hans', prefix=u'de', lname='Wit') m1.mem_email = '*****@*****.**' DBSession.add(m2) wg1 = Workgroup(name=u'Systems', desc=u'IT stuff') DBSession.add(wg1) wg2 = Workgroup(name=u'Besteling', desc=u'Besteling at wholesale') DBSession.add(wg2) DBSession.flush() # flush now to get member and workgroup IDs wg1.members.append(m1) wg1.leaders.append(m1) wg2.members.append(m1) wg2.members.append(m2) wg2.leaders.append(m2) DBSession.flush() s = Shift(wg2.id, 'do stuff', 2012, 6, member=m1) DBSession.add(s) DBSession.flush()
def ActivitySignup(request, activity_id, person_id=None): # TODO: is should be possible to view an activity without loggin in if(person_id is None): # View only mode view_only_mode = True else: view_only_mode = False activity = get_object_or_404(Activity, pk=activity_id) participating = False if(request.resolver_match.url_name == 'activity_view_person'): view_only_mode = True family = user_to_person(request.user).family if person_id: try: person = family.person_set.get(pk=person_id) # Check not already signed up try: participant = ActivityParticipant.objects.get(activity=activity, member__person=person) # found - we can only allow one - switch to view mode participating = True view_only_mode = True except ActivityParticipant.DoesNotExist: participating = False # this was expected - if not signed up yet except Person.DoesNotExist: raise Http404('Person not found on family') else: person = None if(not activity.open_invite): ''' Make sure valid not expired invitation to event exists ''' try: invitation = ActivityInvite.objects.get(activity=activity, person=person, expire_dtm__gte=timezone.now()) except ActivityInvite.DoesNotExist: view_only_mode = True # not invited - switch to view mode invitation = None else: invitation = None # signup_closed should default to False signup_closed = False # if activity is closed for signup, only invited persons can still join if activity.signup_closing < timezone.now().date() and invitation is None: view_only_mode = True # Activivty closed for signup signup_closed = True # check if activity is full if activity.seats_left() <= 0: view_only_mode = True # activity full signup_closed = True if(request.method == "POST"): if view_only_mode: return HttpResponse('Du kan ikke tilmelde dette event nu. (ikke inviteret / tilmelding lukket / du er allerede tilmeldt eller aktiviteten er fuldt booket)') if activity.max_age < person.age_years() or activity.min_age > person.age_years(): return HttpResponse('Barnet skal være mellem ' + str(activity.min_age) + ' og ' + str(activity.max_age) + ' år gammel for at deltage. (Er fødselsdatoen udfyldt korrekt ?)') if Person.objects.filter(family=family).exclude(membertype=Person.CHILD).count() <= 0: return HttpResponse('Barnet skal have en forælder eller værge. Gå tilbage og tilføj en før du tilmelder.') signup_form = ActivitySignupForm(request.POST) if signup_form.is_valid(): # Sign up and redirect to payment link or family page # Calculate membership membership_start = timezone.datetime(year=activity.start_date.year, month=1, day=1) membership_end = timezone.datetime(year=activity.start_date.year, month=12, day=31) # check if person is member, otherwise make a member try: member = Member.objects.get(person=person) except Member.DoesNotExist: member = Member( department=activity.department, person=person, member_since=membership_start, member_until=membership_end, ) member.save() # update membership end date member.member_until = membership_end member.save() # Make ActivityParticipant participant = ActivityParticipant(member=member, activity=activity, note=signup_form.cleaned_data['note']) # If conditions not accepted, make error if signup_form.cleaned_data['read_conditions'] == "NO": return HttpResponse("For at gå til en Coding Pirates aktivitet skal du acceptere vores betingelser.") # Make sure people have selected yes or no in photo permission and update photo permission if signup_form.cleaned_data['photo_permission'] == "Choose": return HttpResponse("Du skal vælge om vi må tage billeder eller ej.") participant.photo_permission = signup_form.cleaned_data['photo_permission'] participant.save() return_link_url = reverse('activity_view_person', args=[activity.id, person.id]) # Make payment if activity costs if activity.price_in_dkk is not None and activity.price_in_dkk != 0: # using creditcard ? if signup_form.cleaned_data['payment_option'] == Payment.CREDITCARD: payment = Payment( payment_type=Payment.CREDITCARD, activity=activity, activityparticipant=participant, person=person, family=family, body_text=timezone.now().strftime("%Y-%m-%d") + ' Betaling for ' + activity.name + ' på ' + activity.department.name, amount_ore=int(activity.price_in_dkk * 100), ) payment.save() return_link_url = payment.get_quickpaytransaction().get_link_url(return_url=settings.BASE_URL + reverse('activity_view_person', args=[activity.id, person.id])) # expire invitation if invitation: invitation.expire_dtm = timezone.now() - timezone.timedelta(days=1) invitation.save() # reject all seasonal invitations on person if this was a seasonal invite # (to avoid signups on multiple departments for club season) if activity.is_season(): invites = ActivityInvite.objects.filter(person=person).exclude(activity=activity) for invite in invites: if invite.activity.is_season(): invite.rejected_dtm = timezone.now() invite.save() return HttpResponseRedirect(return_link_url) # fall through else else: signup_form = ActivitySignupForm() union = activity.department.union context = { 'family': family, 'activity': activity, 'person': person, 'invitation': invitation, 'price': activity.price_in_dkk, 'seats_left': activity.seats_left(), 'signupform': signup_form, 'signup_closed': signup_closed, 'view_only_mode': view_only_mode, 'participating': participating, 'union': union, } return render(request, 'members/activity_signup.html', context)
def __call__(self): self.user_may_edit_admin_settings = self.user.mem_admin return dict(m=Member('', '', ''), msg='')
def ActivitySignup(request, activity_id, unique=None, person_id=None): try: if unique is not None: unique = uuid.UUID(unique) except ValueError: return HttpResponseBadRequest("Familie id er ugyldigt") if (unique is None or person_id is None): # View only mode view_only_mode = True else: view_only_mode = False activity = get_object_or_404(Activity, pk=activity_id) participants = ActivityParticipant.objects.filter( activity=activity).order_by('member__person__name') participating = False if (request.resolver_match.url_name == 'activity_view_person'): view_only_mode = True if unique: family = get_object_or_404(Family, unique=unique) else: family = None if person_id: try: person = family.person_set.get(pk=person_id) # Check not already signed up try: participant = ActivityParticipant.objects.get( activity=activity, member__person=person) # found - we can only allow one - switch to view mode participating = True view_only_mode = True except ActivityParticipant.DoesNotExist: participating = False # this was expected - if not signed up yet except Person.DoesNotExist: raise Http404('Person not found on family') else: person = None if (not activity.open_invite): ''' Make sure valid not expired invitation to event exists ''' try: invitation = ActivityInvite.objects.get( activity=activity, person=person, expire_dtm__gte=timezone.now()) except ActivityInvite.DoesNotExist: view_only_mode = True # not invited - switch to view mode invitation = None else: invitation = None # if activity is closed for signup, only invited persons can still join if activity.signup_closing < timezone.now().date() and invitation is None: view_only_mode = True # Activivty closed for signup signup_closed = True # check if activity is full if activity.seats_left() <= 0: view_only_mode = True # activity full signup_closed = True if (request.method == "POST"): if view_only_mode: return HttpResponse( 'Du kan ikke tilmelde dette event nu. (ikke inviteret / tilmelding lukket / du er allerede tilmeldt eller aktiviteten er fuldt booket)' ) if activity.max_age < person.age_years( ) or activity.min_age > person.age_years(): return HttpResponse( 'Barnet skal være mellem ' + str(activity.min_age) + ' og ' + str(activity.max_age) + ' år gammel for at deltage. (Er fødselsdatoen udfyldt korrekt ?)' ) if Person.objects.filter(family=family).exclude( membertype=Person.CHILD).count() <= 0: return HttpResponse( 'Barnet skal have en forælder eller værge. Gå tilbage og tilføj en før du tilmelder.' ) signup_form = ActivitySignupForm(request.POST) if signup_form.is_valid(): # Sign up and redirect to payment link or family page # Calculate membership membership_start = timezone.datetime(year=activity.start_date.year, month=1, day=1) membership_end = timezone.datetime(year=activity.start_date.year, month=12, day=31) # check if person is member, otherwise make a member try: member = Member.objects.get(person=person) except Member.DoesNotExist: member = Member( department=activity.department, person=person, member_since=membership_start, member_until=membership_end, ) member.save() # update membership end date member.member_until = membership_end member.save() # Make ActivityParticipant participant = ActivityParticipant( member=member, activity=activity, note=signup_form.cleaned_data['note']) # update photo permission and contact open info participant.photo_permission = True # signup_form.cleaned_data['photo_permission'] participant.contact_visible = signup_form.cleaned_data[ 'address_permission'] == "YES" participant.save() return_link_url = reverse( 'activity_view_person', args=[family.unique, activity.id, person.id]) # Make payment if activity costs if activity.price_in_dkk is not None and activity.price_in_dkk != 0: # using creditcard ? if signup_form.cleaned_data[ 'payment_option'] == Payment.CREDITCARD: payment = Payment( payment_type=Payment.CREDITCARD, activity=activity, activityparticipant=participant, person=person, family=family, body_text=timezone.now().strftime("%Y-%m-%d") + ' Betaling for ' + activity.name + ' på ' + activity.department.name, amount_ore=int(activity.price_in_dkk * 100), ) payment.save() return_link_url = payment.get_quickpaytransaction( ).get_link_url( return_url=settings.BASE_URL + reverse('activity_view_person', args=[family.unique, activity.id, person.id])) # expire invitation if invitation: invitation.expire_dtm = timezone.now() - timezone.timedelta( days=1) invitation.save() # reject all seasonal invitations on person if this was a seasonal invite # (to avoid signups on multiple departments for club season) if activity.is_season(): invites = ActivityInvite.objects.filter(person=person).exclude( activity=activity) for invite in invites: if invite.activity.is_season(): invite.rejected_dtm = timezone.now() invite.save() return HttpResponseRedirect(return_link_url) # fall through else else: signup_form = ActivitySignupForm() union = activity.department.union context = { 'family': family, 'activity': activity, 'person': person, 'invitation': invitation, 'price': activity.price_in_dkk, 'seats_left': activity.seats_left(), 'signupform': signup_form, 'view_only_mode': view_only_mode, 'participating': participating, 'participants': participants, 'union': union, } return render(request, 'members/activity_signup.html', context)
def ActivitySignup(request, activity_id, person_id=None): # TODO: is should be possible to view an activity without loggin in if person_id is None: # View only mode view_only_mode = True else: view_only_mode = False activity = get_object_or_404(Activity, pk=activity_id) participating = False if request.resolver_match.url_name == "activity_view_person": view_only_mode = True family = user_to_person(request.user).family if person_id: try: person = family.person_set.get(pk=person_id) # Check not already signed up try: participant = ActivityParticipant.objects.get( activity=activity, member__person=person) # found - we can only allow one - switch to view mode participating = True view_only_mode = True except ActivityParticipant.DoesNotExist: participating = False # this was expected - if not signed up yet except Person.DoesNotExist: raise Http404("Person not found on family") else: person = None if not activity.open_invite: """ Make sure valid not expired invitation to event exists """ try: invitation = ActivityInvite.objects.get( activity=activity, person=person, expire_dtm__gte=timezone.now()) except ActivityInvite.DoesNotExist: view_only_mode = True # not invited - switch to view mode invitation = None else: invitation = None # signup_closed should default to False signup_closed = False # if activity is closed for signup, only invited persons can still join if activity.signup_closing < timezone.now().date() and invitation is None: view_only_mode = True # Activivty closed for signup signup_closed = True # check if activity is full if activity.seats_left() <= 0: view_only_mode = True # activity full signup_closed = True if request.method == "POST": if view_only_mode: return HttpResponse( "Du kan ikke tilmelde dette event nu. (ikke inviteret / tilmelding lukket / du er allerede tilmeldt eller aktiviteten er fuldt booket)" ) if (activity.max_age < person.age_years() or activity.min_age > person.age_years()): return HttpResponse( "Barnet skal være mellem " + str(activity.min_age) + " og " + str(activity.max_age) + " år gammel for at deltage. (Er fødselsdatoen udfyldt korrekt ?)" ) if (Person.objects.filter(family=family).exclude( membertype=Person.CHILD).count() <= 0): return HttpResponse( "Barnet skal have en forælder eller værge. Gå tilbage og tilføj en før du tilmelder." ) signup_form = ActivitySignupForm(request.POST) if signup_form.is_valid(): # Sign up and redirect to payment link or family page # Calculate membership membership_start = timezone.datetime(year=activity.start_date.year, month=1, day=1) membership_end = timezone.datetime(year=activity.start_date.year, month=12, day=31) # check if person is member, otherwise make a member try: member = Member.objects.get(person=person) except Member.DoesNotExist: member = Member( department=activity.department, person=person, member_since=membership_start, member_until=membership_end, ) member.save() # update membership end date member.member_until = membership_end member.save() # Make ActivityParticipant participant = ActivityParticipant( member=member, activity=activity, note=signup_form.cleaned_data["note"]) # If conditions not accepted, make error if signup_form.cleaned_data["read_conditions"] == "NO": return HttpResponse( "For at gå til en Coding Pirates aktivitet skal du acceptere vores betingelser." ) # Make sure people have selected yes or no in photo permission and update photo permission if signup_form.cleaned_data["photo_permission"] == "Choose": return HttpResponse( "Du skal vælge om vi må tage billeder eller ej.") participant.photo_permission = signup_form.cleaned_data[ "photo_permission"] participant.save() return_link_url = reverse("activity_view_person", args=[activity.id, person.id]) # Make payment if activity costs if activity.price_in_dkk is not None and activity.price_in_dkk != 0: # using creditcard ? if signup_form.cleaned_data[ "payment_option"] == Payment.CREDITCARD: payment = Payment( payment_type=Payment.CREDITCARD, activity=activity, activityparticipant=participant, person=person, family=family, body_text=timezone.now().strftime("%Y-%m-%d") + " Betaling for " + activity.name + " på " + activity.department.name, amount_ore=int(activity.price_in_dkk * 100), ) payment.save() return_link_url = payment.get_quickpaytransaction( ).get_link_url(return_url=settings.BASE_URL + reverse( "activity_view_person", args=[activity.id, person.id])) # expire invitation if invitation: invitation.expire_dtm = timezone.now() - timezone.timedelta( days=1) invitation.save() # reject all seasonal invitations on person if this was a seasonal invite # (to avoid signups on multiple departments for club season) if activity.is_season(): invites = ActivityInvite.objects.filter(person=person).exclude( activity=activity) for invite in invites: if invite.activity.is_season(): invite.rejected_dtm = timezone.now() invite.save() return HttpResponseRedirect(return_link_url) # fall through else else: signup_form = ActivitySignupForm() union = activity.department.union context = { "family": family, "activity": activity, "person": person, "invitation": invitation, "price": activity.price_in_dkk, "seats_left": activity.seats_left(), "signupform": signup_form, "signup_closed": signup_closed, "view_only_mode": view_only_mode, "participating": participating, "union": union, } return render(request, "members/activity_signup.html", context)
def fillDBRandomly(seed, workgroups): global default_pwd, fakenames if seed: random.seed(seed) now = datetime.datetime.now() mi = month_info(now.date()) # read in the fakenames names = {} for l in file(fakenames, 'r'): fname, lname = l.strip().split() names[fname] = lname namelist = sorted(list(names.keys())) # 20% of the people are applicants members = [] for l in namelist[int(len(namelist) * 0.2):]: m = Applicant(fname=l, lname=names[l]) m.email = "*****@*****.**" % (l) m.household_size = random.randint(1, 5) m.telnr = "06" + unicode(random.randint(10000000, 100000000)) DBSession.add(m) # randomly select a number of workgroups m can be a member of DBSession.flush() # and the rest are members for l in namelist[:int(len(namelist) * 0.8)]: prefix = random.choice([u"de", u"van", u"voor", u"van den", u"te"]) m = Member(fname=l, prefix=prefix, lname=names[l]) m.mem_email = "*****@*****.**" % (l) m.mem_enc_pwd = md5crypt(default_pwd, default_pwd) m.mem_mobile = "06" + unicode(random.randint(10000000, 100000000)) m.household_size = random.randint(1, 5) m.mem_membership_paid = True if random.random() < 0.01: m.mem_membership_paid = False m.mem_active = True if random.random() < 0.05: m.mem_active = False m.mem_street = random.choice(namelist) + "street" m.mem_house = random.randint(1, 200) m.mem_postcode = "1000AB" m.city = "Amsterdam" DBSession.add(m) # randomly select a number of workgroups m can be a member of for wg in random.sample(workgroups, random.randint(1, len(workgroups))): wg.members.append(m) # randomly select if m is a leader of the workgroup: only 10 % of all members are leaders if random.random() < 0.1: wg.leaders.append(m) members.append(m) DBSession.flush() months = [(mi.prev_month, mi.prev_year), (now.month, now.year), (mi.next_month, mi.next_year)] # next step: create 50 new shifts in each wg with random state/description for wg in workgroups: for i in range(50): task = random.choice([ "clean", "buy", "feed", "fill", "write", "do", "play", "sleep" ]) month = random.choice(months) s = Shift(wg.id, task, month[1], month[0], day=random.randint(1, 30)) s.state = random.choice(shift_states) if not s.state == 'open': s.member = random.choice(wg.members) DBSession.add(s) DBSession.flush()
def fillDBRandomly(seed, workgroups, existing_members): random.seed(seed) now = datetime.datetime.now() mi = month_info(now.date()) # read in the fakenames names = {} for l in open(fakenamesname, 'r').readlines(): fname, lname = l.strip().split() names[fname] = lname namelist = sorted(list(names.keys())) # 20% of the people are applicants members = existing_members for l in namelist[int(len(namelist) * 0.2):]: m = Applicant(fname=l, lname=names[l]) m.email = "*****@*****.**" % (l) m.household_size = random.randint(1, 5) m.telnr = "06" + str(random.randint(10000000, 100000000)) DBSession.add(m) # randomly select a number of workgroups m can be a member of DBSession.flush() # and the rest are members for l in namelist[:int(len(namelist) * 0.8)]: prefix = random.choice([u"de", u"van", u"voor", u"van den", u"te"]) m = Member(fname=l, prefix=prefix, lname=names[l]) m.mem_email = "*****@*****.**" % (l) m.mem_enc_pwd = md5_crypt.hash(default_pwd) m.mem_mobile = "06" + str(random.randint(10000000, 100000000)) m.mem_household_size = random.randint(1, 5) m.mem_membership_paid = True if random.random() < 0.01: m.mem_membership_paid = False m.mem_active = True if random.random() < 0.05: m.mem_active = False m.mem_street = random.choice(namelist) + "street" m.mem_house = random.randint(1, 200) m.mem_postcode = "1000AB" m.mem_city = "Amsterdam" DBSession.add(m) # randomly select a number of workgroups m can be a member of for wg in random.sample(workgroups, random.randint(1, len(workgroups))): wg.members.append(m) # randomly select if m is a leader of the workgroup: only 10 % of all members are leaders if random.random() < 0.1: wg.leaders.append(m) members.append(m) DBSession.flush() months = [(mi.prev_month, mi.prev_year), (now.month, now.year), (mi.next_month, mi.next_year)] # next step: create 50 new shifts in each wg with random state/description for wg in workgroups: for i in range(50): task = random.choice([ "clean", "buy", "feed", "fill", "write", "do", "play", "sleep" ]) month = random.choice(months) s = Shift(wg.id, task, month[1], month[0], day=random.randint(1, 30)) s.state = random.choice(shift_states) if not s.state == 'open': s.member = random.choice(wg.members) DBSession.add(s) DBSession.flush() # Finally: create 20 transactions per member ttype = DBSession.query(TransactionType).filter( TransactionType.name == 'Order Charge').first() orders = DBSession.query(Order).all() for m in members: for i in range(20): month = random.choice(months) t = Transaction(ttype_id=ttype.id, amount=random.random() * 150, date=datetime.datetime(month[1], month[0], random.randint(1, 28)), mem_id=m.mem_id) t.ttype = ttype t.member = m if ttype.pos_neg == 'neg': t.amount *= -1 if ttype.name == 'Order Charge': o = random.choice(orders) t.ord_no = o.id t.order = o t.validate() DBSession.add(t) DBSession.flush()