idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
236,400 | def getEmailTemplate ( request ) : if request . method != 'POST' : return HttpResponse ( _ ( 'Error, no POST data.' ) ) if not hasattr ( request , 'user' ) : return HttpResponse ( _ ( 'Error, not authenticated.' ) ) template_id = request . POST . get ( 'template' ) if not template_id : return HttpResponse ( _ ( "Error,... | This function handles the Ajax call made when a user wants a specific email template |
236,401 | def dispatch ( self , request , * args , ** kwargs ) : paymentSession = request . session . get ( INVOICE_VALIDATION_STR , { } ) self . invoiceID = paymentSession . get ( 'invoiceID' ) self . amount = paymentSession . get ( 'amount' , 0 ) self . success_url = paymentSession . get ( 'success_url' , reverse ( 'registrati... | Check that a valid Invoice ID has been passed in session data and that said invoice is marked as paid . |
236,402 | def form_valid ( self , form ) : emailTo = form . cleaned_data . get ( 'emailTo' ) emailType = form . cleaned_data . get ( 'emailType' ) recipientName = form . cleaned_data . get ( 'recipientName' ) fromName = form . cleaned_data . get ( 'fromName' ) message = form . cleaned_data . get ( 'message' ) logger . info ( 'Pr... | Create the gift certificate voucher with the indicated information and send the email as directed . |
236,403 | def updateSeriesRegistrationStatus ( ) : from . models import Series if not getConstant ( 'general__enableCronTasks' ) : return logger . info ( 'Checking status of Series that are open for registration.' ) open_series = Series . objects . filter ( ) . filter ( ** { 'registrationOpen' : True } ) for series in open_serie... | Every hour check if the series that are currently open for registration should be closed . |
236,404 | def clearExpiredTemporaryRegistrations ( ) : from . models import TemporaryRegistration if not getConstant ( 'general__enableCronTasks' ) : return if getConstant ( 'registration__deleteExpiredTemporaryRegistrations' ) : TemporaryRegistration . objects . filter ( expirationDate__lte = timezone . now ( ) - timedelta ( mi... | Every hour look for TemporaryRegistrations that have expired and delete them . To ensure that there are no issues that arise from slight differences between session expiration dates and TemporaryRegistration expiration dates only delete instances that have been expired for one minute . |
236,405 | def updateFinancialItems ( ) : if not getConstant ( 'general__enableCronTasks' ) : return logger . info ( 'Creating automatically-generated financial items.' ) if getConstant ( 'financial__autoGenerateExpensesEventStaff' ) : createExpenseItemsForEvents ( ) if getConstant ( 'financial__autoGenerateExpensesVenueRental' )... | Every hour create any necessary revenue items and expense items for activities that need them . |
236,406 | def emailErrorMessage ( subject , message ) : if not getConstant ( 'email__enableErrorEmails' ) : logger . info ( 'Not sending error email: error emails are not enabled.' ) return send_from = getConstant ( 'email__errorEmailFrom' ) send_to = getConstant ( 'email__errorEmailTo' ) if not send_from or not send_to : logger... | Useful for sending error messages via email . |
236,407 | def get ( self , request , * args , ** kwargs ) : try : year = int ( self . kwargs . get ( 'year' ) ) except ( ValueError , TypeError ) : year = getIntFromGet ( request , 'year' ) kwargs . update ( { 'year' : year , 'basis' : request . GET . get ( 'basis' ) , } ) if kwargs . get ( 'basis' ) not in EXPENSE_BASES . keys ... | Allow passing of basis and time limitations |
236,408 | def get ( self , request , * args , ** kwargs ) : try : year = int ( self . kwargs . get ( 'year' ) ) except ( ValueError , TypeError ) : year = getIntFromGet ( request , 'year' ) if self . kwargs . get ( 'month' ) : try : month = int ( self . kwargs . get ( 'month' ) ) except ( ValueError , TypeError ) : try : month =... | Pass any permissable GET data . URL parameters override GET parameters |
236,409 | def get_form_kwargs ( self , ** kwargs ) : kwargs = super ( CompensationActionView , self ) . get_form_kwargs ( ** kwargs ) kwargs [ 'staffmembers' ] = self . queryset return kwargs | pass the list of staff members along to the form |
236,410 | def setReminder ( self , occurrence ) : sendReminderTo = self [ 0 ] . cleaned_data [ 'sendReminderTo' ] sendReminderWhen = self [ 0 ] . cleaned_data [ 'sendReminderWhen' ] sendReminderGroup = self [ 0 ] . cleaned_data [ 'sendReminderGroup' ] sendReminderUsers = self [ 0 ] . cleaned_data [ 'sendReminderUsers' ] new_remi... | This function is called to create the actual reminders for each occurrence that is created . |
236,411 | def getIntFromGet ( request , key ) : try : return int ( request . GET . get ( key ) ) except ( ValueError , TypeError ) : return None | This function just parses the request GET data for the requested key and returns it as an integer returning none if the key is not available or is in incorrect format . |
236,412 | def getDateTimeFromGet ( request , key ) : if request . GET . get ( key , '' ) : try : return ensure_timezone ( datetime . strptime ( unquote ( request . GET . get ( key , '' ) ) , '%Y-%m-%d' ) ) except ( ValueError , TypeError ) : pass return None | This function just parses the request GET data for the requested key and returns it in datetime format returning none if the key is not available or is in incorrect format . |
236,413 | def finalizePrivateLessonRegistration ( sender , ** kwargs ) : finalReg = kwargs . pop ( 'registration' ) for er in finalReg . eventregistration_set . filter ( event__privatelessonevent__isnull = False ) : er . event . finalizeBooking ( eventRegistration = er , notifyStudent = False ) | Once a private lesson registration is finalized mark the slots that were used to book the private lesson as booked and associate them with the final registration . No need to notify students in this instance because they are already receiving a notification of their registration . |
236,414 | def resetStaffCompensationInfo ( self , request , queryset ) : selected = request . POST . getlist ( admin . ACTION_CHECKBOX_NAME ) ct = ContentType . objects . get_for_model ( queryset . model ) return HttpResponseRedirect ( reverse ( 'resetCompensationRules' ) + "?ct=%s&ids=%s" % ( ct . pk , "," . join ( selected ) )... | This action is added to the list for staff member to permit bulk reseting to category defaults of compensation information for staff members . |
236,415 | def get_fieldsets ( self , request , obj = None ) : if ( hasattr ( self , 'declared_fieldset' ) and self . declared_fieldsets ) or not self . base_fieldsets : return super ( PolymorphicChildModelAdmin , self ) . get_fieldsets ( request , obj ) other_fields = self . get_subclass_fields ( request , obj ) if other_fields ... | Override polymorphic default to put the subclass - specific fields first |
236,416 | def pattern_input ( self , question , message = 'Invalid entry' , pattern = '^[a-zA-Z0-9_ ]+$' , default = '' , required = True ) : result = '' requiredFlag = True while ( not result and requiredFlag ) : result = input ( '%s: ' % question ) if result and pattern and not re . match ( pattern , result ) : self . stdout .... | Method for input disallowing special characters with optionally specifiable regex pattern and error message . |
236,417 | def float_input ( self , question , message = 'Invalid entry' , default = None , required = True ) : float_result = None requiredFlag = True while ( float_result is None and requiredFlag ) : result = input ( '%s: ' % question ) if not result and not required : float_result = None requiredFlag = False if not result and ... | Method for floating point inputs with optionally specifiable error message . |
236,418 | def ensure_timezone ( dateTime , timeZone = None ) : if is_aware ( dateTime ) and not getattr ( settings , 'USE_TZ' , False ) : return make_naive ( dateTime , timezone = timeZone ) if is_naive ( dateTime ) and getattr ( settings , 'USE_TZ' , False ) : return make_aware ( dateTime , timezone = timeZone ) return dateTime | Since this project is designed to be used in both time - zone aware and naive environments this utility just returns a datetime as either aware or naive depending on whether time zone support is enabled . |
236,419 | def update_payTo ( apps , schema_editor ) : TransactionParty = apps . get_model ( 'financial' , 'TransactionParty' ) ExpenseItem = apps . get_model ( 'financial' , 'ExpenseItem' ) RevenueItem = apps . get_model ( 'financial' , 'RevenueItem' ) GenericRepeatedExpense = apps . get_model ( 'financial' , 'GenericRepeatedExp... | With the new TransactionParty model the senders and recipients of financial transactions are held in one place . So we need to loop through old ExpenseItems RevenueItems and GenericRepeatedExpense and move their old party references to the new party model . |
236,420 | def create_initial_category ( apps , schema_editor ) : DiscountCategory = apps . get_model ( 'discounts' , 'DiscountCategory' ) db_alias = schema_editor . connection . alias DiscountCategory . objects . using ( db_alias ) . create ( id = 1 , name = 'General Discounts' , order = 1 , cannotCombine = False ) | Create a default category for existing discounts |
236,421 | def dispatch ( self , request , * args , ** kwargs ) : self . returnJson = ( request . POST . get ( 'json' ) in [ 'true' , True ] ) regonline = getConstant ( 'registration__registrationEnabled' ) if not regonline : returnUrl = reverse ( 'registrationOffline' ) if self . returnJson : return JsonResponse ( { 'status' : '... | Check that registration is online before proceeding . If this is a POST request determine whether the response should be provided in JSON form . |
236,422 | def get_context_data ( self , ** kwargs ) : context = self . get_listing ( ) context [ 'showDescriptionRule' ] = getConstant ( 'registration__showDescriptionRule' ) or 'all' context . update ( kwargs ) self . set_return_page ( 'registration' , _ ( 'Registration' ) ) return super ( ClassRegistrationView , self ) . get_c... | Add the event and series listing data |
236,423 | def get_form_kwargs ( self , ** kwargs ) : kwargs = super ( ClassRegistrationView , self ) . get_form_kwargs ( ** kwargs ) kwargs [ 'user' ] = self . request . user if hasattr ( self . request , 'user' ) else None listing = self . get_listing ( ) kwargs . update ( { 'openEvents' : listing [ 'openEvents' ] , 'closedEven... | Tell the form which fields to render |
236,424 | def get_allEvents ( self ) : if not hasattr ( self , 'allEvents' ) : timeFilters = { 'endTime__gte' : timezone . now ( ) } if getConstant ( 'registration__displayLimitDays' ) or 0 > 0 : timeFilters [ 'startTime__lte' ] = timezone . now ( ) + timedelta ( days = getConstant ( 'registration__displayLimitDays' ) ) self . a... | Splitting this method out to get the set of events to filter allows one to subclass for different subsets of events without copying other logic |
236,425 | def get_listing ( self ) : if not hasattr ( self , 'listing' ) : allEvents = self . get_allEvents ( ) openEvents = allEvents . filter ( registrationOpen = True ) closedEvents = allEvents . filter ( registrationOpen = False ) publicEvents = allEvents . instance_of ( PublicEvent ) allSeries = allEvents . instance_of ( Se... | This function gets all of the information that we need to either render or validate the form . It is structured to avoid duplicate DB queries |
236,426 | def dispatch ( self , request , * args , ** kwargs ) : regSession = self . request . session . get ( REG_VALIDATION_STR , { } ) if not regSession : return HttpResponseRedirect ( reverse ( 'registration' ) ) try : reg = TemporaryRegistration . objects . get ( id = self . request . session [ REG_VALIDATION_STR ] . get ( ... | Always check that the temporary registration has not expired |
236,427 | def get_context_data ( self , ** kwargs ) : context_data = super ( RegistrationSummaryView , self ) . get_context_data ( ** kwargs ) regSession = self . request . session [ REG_VALIDATION_STR ] reg_id = regSession [ "temp_reg_id" ] reg = TemporaryRegistration . objects . get ( id = reg_id ) discount_codes = regSession ... | Pass the initial kwargs then update with the needed registration info . |
236,428 | def dispatch ( self , request , * args , ** kwargs ) : if REG_VALIDATION_STR not in request . session : return HttpResponseRedirect ( reverse ( 'registration' ) ) try : self . temporaryRegistration = TemporaryRegistration . objects . get ( id = self . request . session [ REG_VALIDATION_STR ] . get ( 'temporaryRegistrat... | Require session data to be set to proceed otherwise go back to step 1 . Because they have the same expiration date this also implies that the TemporaryRegistration object is not yet expired . |
236,429 | def form_valid ( self , form ) : reg = self . temporaryRegistration expiry = timezone . now ( ) + timedelta ( minutes = getConstant ( 'registration__sessionExpiryMinutes' ) ) self . request . session [ REG_VALIDATION_STR ] [ "temporaryRegistrationExpiry" ] = expiry . strftime ( '%Y-%m-%dT%H:%M:%S%z' ) self . request . ... | Even if this form is valid the handlers for this form may have added messages to the request . In that case then the page should be handled as if the form were invalid . Otherwise update the session data with the form data and then move to the next view |
236,430 | def linkUserToMostRecentCustomer ( sender , ** kwargs ) : email_address = kwargs . get ( 'email_address' , None ) if not email_address or not email_address . primary or not email_address . verified : return user = email_address . user if not hasattr ( user , 'customer' ) : last_reg = Registration . objects . filter ( c... | If a new primary email address has just been confirmed check if the user associated with that email has an associated customer object yet . If not then look for the customer with that email address who most recently registered for something and that is not associated with another user . Automatically associate the User... |
236,431 | def linkCustomerToVerifiedUser ( sender , ** kwargs ) : registration = kwargs . get ( 'registration' , None ) if not registration or ( hasattr ( registration . customer , 'user' ) and registration . customer . user ) : return logger . debug ( 'Checking for User for Customer with no associated registration.' ) customer ... | If a Registration is processed in which the associated Customer does not yet have a User then check to see if the Customer s email address has been verified as belonging to a specific User and if that User has an associated Customer . If such a User is found then associated this Customer with that User . This way if a ... |
236,432 | def create_object ( self , text ) : if self . create_field == 'fullName' : firstName = text . split ( ' ' ) [ 0 ] lastName = ' ' . join ( text . split ( ' ' ) [ 1 : ] ) return self . get_queryset ( ) . create ( ** { 'firstName' : firstName , 'lastName' : lastName } ) else : return super ( StaffMemberAutoComplete , self... | Allow creation of staff members using a full name string . |
236,433 | def checkBanlist ( sender , ** kwargs ) : if not getConstant ( 'registration__enableBanList' ) : return logger . debug ( 'Signal to check RegistrationContactForm handled by banlist app.' ) formData = kwargs . get ( 'formData' , { } ) first = formData . get ( 'firstName' ) last = formData . get ( 'lastName' ) email = fo... | Check that this individual is not on the ban list . |
236,434 | def clean ( self ) : if self . staffMember and self . staffMember . userAccount and self . user and not self . staffMember . userAccount == self . user : raise ValidationError ( _ ( 'Transaction party user does not match staff member user.' ) ) if self . location and ( self . user or self . staffMember ) : raise Valida... | Verify that the user and staffMember are not mismatched . Location can only be specified if user and staffMember are not . |
236,435 | def save ( self , updateBy = None , * args , ** kwargs ) : if ( self . staffMember and self . staffMember . userAccount and not self . user ) or ( isinstance ( updateBy , StaffMember ) and self . staffMember . userAccount ) : self . user = self . staffMember . userAccount elif ( self . user and getattr ( self . user , ... | Verify that the user and staffMember are populated with linked information and ensure that the name is properly specified . |
236,436 | def ruleName ( self ) : return '%s %s' % ( self . rentalRate , self . RateRuleChoices . values . get ( self . applyRateRule , self . applyRateRule ) ) | This should be overridden for child classes |
236,437 | def ruleName ( self ) : return _ ( '%s at %s' % ( self . room . name , self . room . location . name ) ) | overrides from parent class |
236,438 | def clean ( self ) : if not self . priorDays and not self . startDate : raise ValidationError ( _ ( 'Either a start date or an "up to __ days in the past" limit is required ' + 'for repeated expense rules that are not associated with a venue or a staff member.' ) ) super ( GenericRepeatedExpense , self ) . clean ( ) | priorDays is required for Generic Repeated Expenses to avoid infinite loops |
236,439 | def save ( self , * args , ** kwargs ) : if not hasattr ( self , '__paid' ) or not hasattr ( self , '__approved' ) : if self . approved and not self . approvalDate : self . approvalDate = timezone . now ( ) if self . paid and not self . paymentDate : self . paymentDate = timezone . now ( ) else : if self . approved and... | This custom save method ensures that an expense is not attributed to multiple categories . It also ensures that the series and event properties are always associated with any type of expense of that series or event . |
236,440 | def relatedItems ( self ) : if self . registration : return self . registration . revenueitem_set . exclude ( pk = self . pk ) | If this item is associated with a registration then return all other items associated with the same registration . |
236,441 | def save ( self , * args , ** kwargs ) : if not hasattr ( self , '__received' ) : if self . received and not self . receivedDate : self . receivedDate = timezone . now ( ) else : if self . received and not self . receivedDate and not self . __receivedDate : self . receivedDate = timezone . now ( ) if not self . accrual... | This custom save method ensures that a revenue item is not attributed to multiple categories . It also ensures that the series and event properties are always associated with any type of revenue of that series or event . |
236,442 | def clean ( self ) : super ( SlotCreationForm , self ) . clean ( ) startDate = self . cleaned_data . get ( 'startDate' ) endDate = self . cleaned_data . get ( 'endDate' ) startTime = self . cleaned_data . get ( 'startTime' ) endTime = self . cleaned_data . get ( 'endTime' ) instructor = self . cleaned_data . get ( 'ins... | Only allow submission if there are not already slots in the submitted window and only allow rooms associated with the chosen location . |
236,443 | def get_method_list ( ) : methods = [ str ( _ ( 'Cash' ) ) , str ( _ ( 'Check' ) ) , str ( _ ( 'Bank/Debit Card' ) ) , str ( _ ( 'Other' ) ) ] methods += ExpenseItem . objects . order_by ( ) . values_list ( 'paymentMethod' , flat = True ) . distinct ( ) methods += RevenueItem . objects . order_by ( ) . values_list ( 'p... | Include manual methods by default |
236,444 | def get_create_option ( self , context , q ) : create_option = [ ] display_create_option = False if self . create_field and q : page_obj = context . get ( 'page_obj' , None ) if page_obj is None or page_obj . number == 1 : display_create_option = True if display_create_option and self . has_add_permission ( self . requ... | Form the correct create_option to append to results . |
236,445 | def create_object ( self , text ) : if self . create_field == 'name' : if text . startswith ( 'Location_' ) : this_id = text [ len ( 'Location_' ) : ] this_loc = Location . objects . get ( id = this_id ) return self . get_queryset ( ) . get_or_create ( name = this_loc . name , location = this_loc ) [ 0 ] elif text . st... | Allow creation of transaction parties using a full name string . |
236,446 | def has_group ( user , group_name ) : if user . groups . filter ( name = group_name ) . exists ( ) : return True return False | This allows specification group - based permissions in templates . In most instances creating model - based permissions and giving them to the desired group is preferable . |
236,447 | def get_item_by_key ( passed_list , key , value ) : if value in [ None , '' ] : return if type ( passed_list ) in [ QuerySet , PolymorphicQuerySet ] : sub_list = passed_list . filter ( ** { key : value } ) else : sub_list = [ x for x in passed_list if x . get ( key ) == value ] if len ( sub_list ) == 1 : return sub_lis... | This one allows us to get one or more items from a list of dictionaries based on the value of a specified key where both the key and the value can be variable names . Does not work with None or null string passed values . |
236,448 | def get_field_for_object ( field_type , field_id , form ) : field_name = field_type + '_' + str ( field_id ) return form . __getitem__ ( field_name ) | This tag allows one to get a specific series or event form field in registration views . |
236,449 | def template_exists ( template_name ) : try : template . loader . get_template ( template_name ) return True except template . TemplateDoesNotExist : return False | Determine if a given template exists so that it can be loaded if so or a default alternative can be used if not . |
236,450 | def numRegisteredForRole ( event , role ) : if not isinstance ( event , Event ) or not isinstance ( role , DanceRole ) : return None return event . numRegisteredForRole ( role ) | This tag allows one to access the number of registrations for any dance role . |
236,451 | def soldOutForRole ( event , role ) : if not isinstance ( event , Event ) or not isinstance ( role , DanceRole ) : return None return event . soldOutForRole ( role ) | This tag allows one to determine whether any event is sold out for any particular role . |
236,452 | def numRegisteredForRoleName ( event , roleName ) : if not isinstance ( event , Event ) : return None try : role = DanceRole . objects . get ( name = roleName ) except ObjectDoesNotExist : return None return event . numRegisteredForRole ( role ) | This tag allows one to access the number of registrations for any dance role using only the role s name . |
236,453 | def create_new_code ( cls , ** kwargs ) : prefix = kwargs . pop ( 'prefix' , '' ) new = False while not new : random_string = '' . join ( random . choice ( string . ascii_uppercase ) for z in range ( 10 ) ) if not Voucher . objects . filter ( voucherId = '%s%s' % ( prefix , random_string ) ) . exists ( ) : new = True r... | Creates a new Voucher with a unique voucherId |
236,454 | def customerMeetsRequirement ( self , customer , danceRole = None , registration = None ) : cust_reqs = self . customerrequirement_set . filter ( customer = customer , met = True ) if customer : cust_priors = customer . eventregistration_set . filter ( event__series__isnull = False ) else : cust_priors = EventRegistrat... | This method checks whether a given customer meets a given set of requirements . |
236,455 | def updateTransactionParty ( sender , instance , ** kwargs ) : if 'loaddata' in sys . argv or ( 'raw' in kwargs and kwargs [ 'raw' ] ) : return logger . debug ( 'TransactionParty signal fired for %s %s.' % ( instance . __class__ . __name__ , instance . id ) ) party = getattr ( instance , 'transactionparty' , None ) if ... | If a User StaffMember or Location is updated and there exists an associated TransactionParty then the name and other attributes of that party should be updated to reflect the new information . |
236,456 | def updateSquareFees ( paymentRecord ) : fees = paymentRecord . netFees invoice = paymentRecord . invoice invoice . fees = fees invoice . save ( ) invoice . allocateFees ( ) return fees | The Square Checkout API does not calculate fees immediately so this task is called to be asynchronously run 1 minute after the initial transaction so that any Invoice or ExpenseItem associated with this transaction also remains accurate . |
236,457 | def getClassTypeMonthlyData ( year = None , series = None , typeLimit = None ) : if not year : year = timezone . now ( ) . year role_list = DanceRole . objects . distinct ( ) if series not in [ 'registrations' , 'studenthours' ] and series not in [ x . pluralName for x in role_list ] : series = 'registrations' when_all... | To break out by class type and month simultaneously get data for each series and aggregate by class type . |
236,458 | def form_valid ( self , form ) : startDate = form . cleaned_data [ 'startDate' ] endDate = form . cleaned_data [ 'endDate' ] startTime = form . cleaned_data [ 'startTime' ] endTime = form . cleaned_data [ 'endTime' ] instructor = form . cleaned_data [ 'instructorId' ] interval_minutes = getConstant ( 'privateLessons__l... | Create slots and return success message . |
236,459 | def form_valid ( self , form ) : slotIds = form . cleaned_data [ 'slotIds' ] deleteSlot = form . cleaned_data . get ( 'deleteSlot' , False ) these_slots = InstructorAvailabilitySlot . objects . filter ( id__in = slotIds ) if deleteSlot : these_slots . delete ( ) else : for this_slot in these_slots : this_slot . locatio... | Modify or delete the availability slot as requested and return success message . |
236,460 | def get_form_kwargs ( self , ** kwargs ) : kwargs = super ( BookPrivateLessonView , self ) . get_form_kwargs ( ** kwargs ) kwargs [ 'user' ] = self . request . user if hasattr ( self . request , 'user' ) else None return kwargs | Pass the current user to the form to render the payAtDoor field if applicable . |
236,461 | def dispatch ( self , request , * args , ** kwargs ) : lessonSession = request . session . get ( PRIVATELESSON_VALIDATION_STR , { } ) try : self . lesson = PrivateLessonEvent . objects . get ( id = lessonSession . get ( 'lesson' ) ) except ( ValueError , ObjectDoesNotExist ) : messages . error ( request , _ ( 'Invalid ... | Handle the session data passed by the prior view . |
236,462 | def get_object ( self , queryset = None ) : return get_object_or_404 ( GuestList . objects . filter ( id = self . kwargs . get ( 'guestlist_id' ) ) ) | Get the guest list from the URL |
236,463 | def get_context_data ( self , ** kwargs ) : event = Event . objects . filter ( id = self . kwargs . get ( 'event_id' ) ) . first ( ) if self . kwargs . get ( 'event_id' ) and not self . object . appliesToEvent ( event ) : raise Http404 ( _ ( 'Invalid event.' ) ) if not event : event = self . object . currentEvent conte... | Add the list of names for the given guest list |
236,464 | def getBasePrice ( self , ** kwargs ) : if not self . pricingTier : return None return self . pricingTier . getBasePrice ( ** kwargs ) * max ( self . numSlots , 1 ) | This method overrides the method of the base Event class by checking the pricingTier associated with this PrivateLessonEvent and getting the appropriate price for it . |
236,465 | def customers ( self ) : return Customer . objects . filter ( Q ( privatelessoncustomer__lesson = self ) | Q ( registration__eventregistration__event = self ) ) . distinct ( ) | List both any individuals signed up via the registration and payment system and any individuals signed up without payment . |
236,466 | def save ( self , * args , ** kwargs ) : if not self . status : self . status == Event . RegStatus . hidden super ( PrivateLessonEvent , self ) . save ( * args , ** kwargs ) | Set registration status to hidden if it is not specified otherwise |
236,467 | def availableDurations ( self ) : potential_slots = InstructorAvailabilitySlot . objects . filter ( instructor = self . instructor , location = self . location , room = self . room , pricingTier = self . pricingTier , startTime__gte = self . startTime , startTime__lte = self . startTime + timedelta ( minutes = getConst... | A lesson can always be booked for the length of a single slot but this method checks if multiple slots are available . This method requires that slots are non - overlapping which needs to be enforced on slot save . |
236,468 | def availableRoles ( self ) : if not hasattr ( self . instructor , 'instructorprivatelessondetails' ) : return [ ] return [ [ x . id , x . name ] for x in self . instructor . instructorprivatelessondetails . roles . all ( ) ] | Some instructors only offer private lessons for certain roles so we should only allow booking for the roles that have been selected for the instructor . |
236,469 | def checkIfAvailable ( self , dateTime = timezone . now ( ) ) : return ( self . startTime >= dateTime + timedelta ( days = getConstant ( 'privateLessons__closeBookingDays' ) ) and self . startTime <= dateTime + timedelta ( days = getConstant ( 'privateLessons__openBookingDays' ) ) and not self . eventRegistration and (... | Available slots are available but also tentative slots that have been held as tentative past their expiration date |
236,470 | def json_event_feed ( request , location_id = None , room_id = None ) : if not getConstant ( 'calendar__privateCalendarFeedEnabled' ) or not request . user . is_staff : return JsonResponse ( { } ) this_user = request . user startDate = request . GET . get ( 'start' , '' ) endDate = request . GET . get ( 'end' , '' ) ti... | The Jquery fullcalendar app requires a JSON news feed so this function creates the feed from upcoming PrivateEvent objects |
236,471 | def checkRequirements ( sender , ** kwargs ) : if not getConstant ( 'requirements__enableRequirements' ) : return logger . debug ( 'Signal to check RegistrationContactForm handled by prerequisites app.' ) formData = kwargs . get ( 'formData' , { } ) first = formData . get ( 'firstName' ) last = formData . get ( 'lastNa... | Check that the customer meets all prerequisites for the items in the registration . |
236,472 | def get_email_context ( self , ** kwargs ) : context = kwargs context . update ( { 'currencyCode' : getConstant ( 'general__currencyCode' ) , 'currencySymbol' : getConstant ( 'general__currencySymbol' ) , 'businessName' : getConstant ( 'contact__businessName' ) , 'site_url' : getConstant ( 'email__linkProtocol' ) + ':/... | This method can be overridden in classes that inherit from this mixin so that additional object - specific context is provided to the email template . This should return a dictionary . By default only general financial context variables are added to the dictionary and kwargs are just passed directly . Note also that it... |
236,473 | def get_group_required ( self ) : this_object = self . model_object if hasattr ( this_object , self . group_required_field ) : if hasattr ( getattr ( this_object , self . group_required_field ) , 'name' ) : return [ getattr ( this_object , self . group_required_field ) . name ] return [ '' ] | Get the group_required value from the object |
236,474 | def check_membership ( self , groups ) : if not groups or groups == [ '' ] : return True if self . request . user . is_superuser : return True user_groups = self . request . user . groups . values_list ( "name" , flat = True ) return set ( groups ) . intersection ( set ( user_groups ) ) | Allows for objects with no required groups |
236,475 | def dispatch ( self , request , * args , ** kwargs ) : self . request = request in_group = False required_group = self . get_group_required ( ) if not required_group or required_group == [ '' ] : in_group = True elif self . request . user . is_authenticated ( ) : in_group = self . check_membership ( required_group ) if... | This override of dispatch ensures that if no group is required then the request still goes through without being logged in . |
236,476 | def validate ( self , value ) : super ( ChoiceField , self ) . validate ( value ) try : get_template ( value ) except TemplateDoesNotExist : raise ValidationError ( _ ( '%s is not a valid template.' % value ) ) | Check for empty values and for an existing template but do not check if this is one of the initial choices provided . |
236,477 | def render ( self , context , instance , placeholder ) : if instance and instance . template : self . render_template = instance . template return super ( PluginTemplateMixin , self ) . render ( context , instance , placeholder ) | Permits setting of the template in the plugin instance configuration |
236,478 | def get_return_page ( self , prior = False ) : siteHistory = self . request . session . get ( 'SITE_HISTORY' , { } ) return getReturnPage ( siteHistory , prior = prior ) | This is just a wrapper for the getReturnPage helper function . |
236,479 | def is_valid ( self ) : valid = super ( RegistrationContactForm , self ) . is_valid ( ) msgs = messages . get_messages ( self . _request ) prior_messages = self . _session . pop ( 'prior_messages' , [ ] ) remaining_messages = [ ] for m in msgs : m_dict = { 'message' : m . message , 'level' : m . level , 'extra_tags' : ... | For this form to be considered valid there must be not only no errors but also no messages on the request that need to be shown . |
236,480 | def clean_total_refund_amount ( self ) : initial = self . cleaned_data . get ( 'initial_refund_amount' , 0 ) total = self . cleaned_data [ 'total_refund_amount' ] summed_refunds = sum ( [ v for k , v in self . cleaned_data . items ( ) if k . startswith ( 'item_refundamount_' ) ] ) if not self . cleaned_data . get ( 'id... | The Javascript should ensure that the hidden input is updated but double check it here . |
236,481 | def clean ( self ) : super ( SubstituteReportingForm , self ) . clean ( ) occurrences = self . cleaned_data . get ( 'occurrences' , [ ] ) staffMember = self . cleaned_data . get ( 'staffMember' ) replacementFor = self . cleaned_data . get ( 'replacedStaffMember' , [ ] ) event = self . cleaned_data . get ( 'event' ) for... | This code prevents multiple individuals from substituting for the same class and class teacher . It also prevents an individual from substituting for a class in which they are a teacher . |
236,482 | def save ( self , commit = True ) : existing_record = EventStaffMember . objects . filter ( staffMember = self . cleaned_data . get ( 'staffMember' ) , event = self . cleaned_data . get ( 'event' ) , category = getConstant ( 'general__eventStaffCategorySubstitute' ) , replacedStaffMember = self . cleaned_data . get ( '... | If a staff member is reporting substitute teaching for a second time then we should update the list of occurrences for which they are a substitute on their existing EventStaffMember record rather than creating a new record and creating database issues . |
236,483 | def save ( self , commit = True ) : if getattr ( self . instance , 'instructor' , None ) : self . instance . instructor . availableForPrivates = self . cleaned_data . pop ( 'availableForPrivates' , self . instance . instructor . availableForPrivates ) self . instance . instructor . save ( update_fields = [ 'availableFo... | If the staff member is an instructor also update the availableForPrivates field on the Instructor record . |
236,484 | def save ( self , * args , ** kwargs ) : if not self . pluralName : self . pluralName = self . name + 's' super ( self . __class__ , self ) . save ( * args , ** kwargs ) | Just add s if no plural name given . |
236,485 | def getBasePrice ( self , ** kwargs ) : payAtDoor = kwargs . get ( 'payAtDoor' , False ) dropIns = kwargs . get ( 'dropIns' , 0 ) if dropIns : return dropIns * self . dropinPrice if payAtDoor : return self . doorPrice return self . onlinePrice | This handles the logic of finding the correct price . If more sophisticated discounting systems are needed then this PricingTier model can be subclassed or the discounts and vouchers apps can be used . |
236,486 | def availableRoles ( self ) : eventRoles = self . eventrole_set . filter ( capacity__gt = 0 ) if eventRoles . count ( ) > 0 : return [ x . role for x in eventRoles ] elif isinstance ( self , Series ) : return self . classDescription . danceTypeLevel . danceType . roles . all ( ) return [ ] | Returns the set of roles for this event . Since roles are not always custom specified for event this looks for the set of available roles in multiple places . If no roles are found then the method returns an empty list in which case it can be assumed that the event s registration is not role - specific . |
236,487 | def numRegisteredForRole ( self , role , includeTemporaryRegs = False ) : count = self . eventregistration_set . filter ( cancelled = False , dropIn = False , role = role ) . count ( ) if includeTemporaryRegs : count += self . temporaryeventregistration_set . filter ( dropIn = False , role = role ) . exclude ( registra... | Accepts a DanceRole object and returns the number of registrations of that role . |
236,488 | def capacityForRole ( self , role ) : if isinstance ( role , DanceRole ) : role_id = role . id else : role_id = role eventRoles = self . eventrole_set . filter ( capacity__gt = 0 ) if eventRoles . count ( ) > 0 and role_id not in [ x . role . id for x in eventRoles ] : return 0 elif eventRoles . count ( ) > 0 : return ... | Accepts a DanceRole object and determines the capacity for that role at this event . this Since roles are not always custom specified for events this looks for the set of available roles in multiple places and only returns the overall capacity of the event if roles are not found elsewhere . |
236,489 | def soldOutForRole ( self , role , includeTemporaryRegs = False ) : return self . numRegisteredForRole ( role , includeTemporaryRegs = includeTemporaryRegs ) >= ( self . capacityForRole ( role ) or 0 ) | Accepts a DanceRole object and responds if the number of registrations for that role exceeds the capacity for that role at this event . |
236,490 | def allDayForDate ( self , this_date , timeZone = None ) : if isinstance ( this_date , datetime ) : d = this_date . date ( ) else : d = this_date date_start = datetime ( d . year , d . month , d . day ) naive_start = self . startTime if timezone . is_naive ( self . startTime ) else timezone . make_naive ( self . startT... | This method determines whether the occurrence lasts the entirety of a specified day in the specified time zone . If no time zone is specified then it uses the default time zone ) . Also give a grace period of a few minutes to account for issues with the way events are sometimes entered . |
236,491 | def netHours ( self ) : if self . specifiedHours is not None : return self . specifiedHours elif self . category in [ getConstant ( 'general__eventStaffCategoryAssistant' ) , getConstant ( 'general__eventStaffCategoryInstructor' ) ] : return self . event . duration - sum ( [ sub . netHours for sub in self . replacement... | For regular event staff this is the net hours worked for financial purposes . For Instructors netHours is caclulated net of any substitutes . |
236,492 | def shortDescription ( self ) : cd = getattr ( self , 'classDescription' , None ) if cd : sd = getattr ( cd , 'shortDescription' , '' ) d = getattr ( cd , 'description' , '' ) return sd if sd else d return '' | Overrides property from Event base class . |
236,493 | def netHours ( self ) : if self . specifiedHours is not None : return self . specifiedHours return self . event . duration - sum ( [ sub . netHours for sub in self . replacementFor . all ( ) ] ) | For regular event staff this is the net hours worked for financial purposes . For Instructors netHours is calculated net of any substitutes . |
236,494 | def getTimeOfClassesRemaining ( self , numClasses = 0 ) : occurrences = EventOccurrence . objects . filter ( cancelled = False , event__in = [ x . event for x in self . temporaryeventregistration_set . filter ( event__series__isnull = False ) ] , ) . order_by ( '-endTime' ) if occurrences . count ( ) > numClasses : ret... | For checking things like prerequisites it s useful to check if a requirement is almost met |
236,495 | def finalize ( self , ** kwargs ) : dateTime = kwargs . pop ( 'dateTime' , timezone . now ( ) ) sendEmail = kwargs . pop ( 'sendEmail' , True ) customer , created = Customer . objects . update_or_create ( first_name = self . firstName , last_name = self . lastName , email = self . email , defaults = { 'phone' : self . ... | This method is called when the payment process has been completed and a registration is ready to be finalized . It also fires the post - registration signal |
236,496 | def save ( self , * args , ** kwargs ) : if self . send_html : self . content = get_text_for_html ( self . html_content ) else : self . html_content = None super ( EmailTemplate , self ) . save ( * args , ** kwargs ) | If this is an HTML template then set the non - HTML content to be the stripped version of the HTML . If this is a plain text template then set the HTML content to be null . |
236,497 | def create_from_registration ( cls , reg , ** kwargs ) : submissionUser = kwargs . pop ( 'submissionUser' , None ) collectedByUser = kwargs . pop ( 'collectedByUser' , None ) status = kwargs . pop ( 'status' , Invoice . PaymentStatus . unpaid ) new_invoice = cls ( firstName = reg . firstName , lastName = reg . lastName... | Handles the creation of an Invoice as well as one InvoiceItem per assodciated TemporaryEventRegistration or registration . Also handles taxes appropriately . |
236,498 | def url ( self ) : if self . id : return '%s://%s%s' % ( getConstant ( 'email__linkProtocol' ) , Site . objects . get_current ( ) . domain , reverse ( 'viewInvoice' , args = [ self . id , ] ) , ) | Because invoice URLs are generally emailed this includes the default site URL and the protocol specified in settings . |
236,499 | def calculateTaxes ( self ) : tax_rate = ( getConstant ( 'registration__salesTaxRate' ) or 0 ) / 100 if tax_rate > 0 : if self . buyerPaysSalesTax : self . taxes = self . total * tax_rate else : adjusted_total = self . total / ( 1 + tax_rate ) self . taxes = adjusted_total * tax_rate | Updates the tax field to reflect the amount of taxes depending on the local rate as well as whether the buyer or seller pays sales tax . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.