def instantvisit(request): chapter = request.user.chapter # Check if the user has exec rights if not request.user.is_staff and not request.user.is_superuser: raise Http404 if not request.session.get('hoursPerPersonStage', False): request.session['hoursPerPersonStage'] = 1 # Sometimes request.session['hoursPerPersonStage'] may equal 1 from editing stats from a closed workshop if request.method == 'POST' and request.session['hoursPerPersonStage'] != 2: if request.user.is_superuser: formpart1 = SchoolVisitFormInstant(request.POST, chapter=None) formpart2 = SchoolVisitStatsFormInstant(request.POST, chapter=None) else: formpart1 = SchoolVisitFormInstant(request.POST, chapter=chapter) formpart2 = SchoolVisitStatsFormInstant(request.POST, chapter=chapter) form_school = SchoolFormPartOne(request.POST, chapter=chapter, school_id=0) # Validate form if formpart1.is_valid() and formpart2.is_valid(): data = formpart1.cleaned_data data_stats = formpart2.cleaned_data selected_school = data['school'] school_visit = SchoolVisit() new_school = School() school_visit.created_method = 1 # Check if new school was selected, New school equals to 0 if selected_school == u'0': if form_school.is_valid(): new_school_form = form_school.cleaned_data # Check if school exists exist = School.objects.filter( name__iexact=new_school_form['name'], chapter=chapter) if exist: messages.error( request, "School seems to already exist, please recheck list." ) return render_to_response( 'instant_workshop.html', { 'form1': formpart1, 'form2': formpart2, 'schoolform': form_school }, context_instance=RequestContext(request)) # Create new school after checking it doesn't exist new_school.name = new_school_form['name'] new_school.chapter = chapter new_school.address_street = new_school_form[ 'address_street'] new_school.address_city = new_school_form['address_city'] new_school.address_state = new_school_form['address_state'] new_school.address_country = new_school_form[ 'address_country'] new_school.save() school_visit.school = new_school else: # School form invalid return render_to_response( 'instant_workshop.html', { 'form1': formpart1, 'form2': formpart2, 'schoolform': form_school }, context_instance=RequestContext(request)) else: try: previously_visited_school = School.objects.get( name=selected_school) except ObjectDoesNotExist: messages.error( request, message=unicode( "Please select a school from the list or create a new one." )) return render_to_response( 'instant_workshop.html', { 'form1': formpart1, 'form2': formpart2, 'schoolform': form_school }, context_instance=RequestContext(request)) school_visit.school = previously_visited_school school_visit.chapter = chapter school_visit.creator = request.user school_visit.location = data['location'] school_visit.visit_start = make_aware(datetime.datetime.combine( data['date'], data['start_time']), timezone=chapter.tz_obj()) school_visit.visit_end = make_aware(datetime.datetime.combine( data['date'], data['end_time']), timezone=chapter.tz_obj()) school_visit.save() # Add the new stats just entered stats = SchoolVisitStats() stats.visit = school_visit stats.visit_type = data_stats['visit_type'] stats.primary_girls_first = data_stats['primary_girls_first'] stats.primary_girls_repeat = data_stats['primary_girls_repeat'] stats.primary_boys_first = data_stats['primary_boys_first'] stats.primary_boys_repeat = data_stats['primary_boys_repeat'] stats.high_girls_first = data_stats['high_girls_first'] stats.high_girls_repeat = data_stats['high_girls_repeat'] stats.high_boys_first = data_stats['high_boys_first'] stats.high_boys_repeat = data_stats['high_boys_repeat'] stats.other_girls_first = data_stats['other_girls_first'] stats.other_girls_repeat = data_stats['other_girls_repeat'] stats.other_boys_first = data_stats['other_boys_first'] stats.other_boys_repeat = data_stats['other_boys_repeat'] stats.notes = data_stats['notes'] stats.save() # Save attendance in database for attendee in data_stats['attended']: newinvite = EventAttendee() newinvite.event = school_visit newinvite.user = attendee newinvite.actual_status = 1 newinvite.rsvp_status = 0 newinvite.save() # Render page 2: enter user-specific volunteering hours default_hours = int( math.ceil((school_visit.visit_end - school_visit.visit_start).total_seconds() / 3600.0)) request.session['hoursPerPersonStage'] = 2 return render_to_response('visit_hoursPerPerson.html', { 'attended': data_stats['attended'], 'visit_id': school_visit.id, 'defaultHours': range(default_hours) }, context_instance=RequestContext(request)) # Form is invalid else: return render_to_response('instant_workshop.html', { 'form1': formpart1, 'form2': formpart2, 'schoolform': form_school }, context_instance=RequestContext(request)) # Happens when someone presses back - refer them to the workshop list page to refill stats there elif request.method == 'POST' and request.session[ 'hoursPerPersonStage'] == 2: del request.session['hoursPerPersonStage'] messages.info( request, message= 'An error occurred, find your newly created workshop here and refill in your stats.' ) return redirect('/teaching/list/') # Prepare form if request.user.is_superuser: formpart1 = SchoolVisitFormInstant(chapter=None) formpart2 = SchoolVisitStatsFormInstant(chapter=None) else: formpart1 = SchoolVisitFormInstant(chapter=chapter) formpart2 = SchoolVisitStatsFormInstant(chapter=chapter) form_school = SchoolFormPartOne(chapter=chapter, school_id=0) # Render clean form return render_to_response('instant_workshop.html', { 'form1': formpart1, 'form2': formpart2, 'schoolform': form_school }, context_instance=RequestContext(request))
def import_workshop_csv(request, filerows, save): columns = None workshops_imported = 0 workshop_list = [] err_msg = {} row_idx = 0 # Find the indices of fields for row in filerows: if any(row): row_idx += 1 if columns is None: columns = row # Check to see there are an appropriate number of columns in the header if len(columns) < 20: err_msg.update({ str(row_idx): 'You are missing columns in your .csv table. Please correct the error and try again.' }) workshops_imported = None return workshop_list, workshops_imported, err_msg continue school_visit = SchoolVisit() stats = SchoolVisitStats() school_visit.chapter = request.user.chapter school_visit.creator = request.user school_visit.created_method = 2 i = 0 date = '' attendees_list = [] attendee_errors = {} data_filled_correctly = False for col in row: colname = columns[i] i += 1 if i > 19: i = 19 if 'Attendees' in colname: if i != 19: err_msg.update({ str(row_idx): 'There was an incorrect number of items in this row, please check your columns from template again' }) break # ASSUMPTION: The remaining columns in a row are all volunteer usernames data_filled_correctly = True attendee = EventAttendee() try: # Empty attendee field if not col: continue # Try to find in the user exists u = User.objects.get(username__exact=col) except ObjectDoesNotExist: try: attendee_errors[str( row_idx )] += '<br>Could not find %s and has not been added to the workshop' % col except KeyError: attendee_errors.update({ str(row_idx): 'Could not find %s and has not been added to the workshop' % col }) continue attendee.user = u attendee.actual_status = 1 attendee.rsvp_status = 0 attendees_list.append(attendee) else: if colname == 'School ID': try: school_visit.school = School.objects.get( pk=sint(col), chapter=request.user.chapter) except ObjectDoesNotExist: err_msg.update({ str(row_idx): "That school ID does not exist in your schools database, please check again from your schools list. If they don't exist, add them in the Schools tab and try again" }) break elif colname == 'Visit Date': # Check for correct format try: date = datetime.strptime(col, '%d/%m/%Y') except ValueError: err_msg.update({ str(row_idx): 'The date format specified (%s) is not in the correct format' % col }) break # Check if user enters an event that's set in the future if make_aware( date, timezone=request.user.chapter.tz_obj() ) > datetime.now(tz=request.user.chapter.tz_obj()): err_msg.update({ str(row_idx): 'This event has not occurred yet and therefore cannot be entered in' }) break elif colname == 'Start Time': # Check for correct format try: t = datetime.strptime(col, '%H:%M:%S').time() except ValueError: try: # Try another format cause excel -_- t = datetime.strptime(col, '%H:%M').time() except ValueError: err_msg.update({ str(row_idx): 'The start time specified (%s) is not in the correct format' % col }) break school_visit.visit_start = make_aware( datetime.combine(date, t), timezone=request.user.chapter.tz_obj()) elif colname == 'End Time': # Check for correct format try: t = datetime.strptime(col, '%H:%M:%S').time() except ValueError: try: # Try another format cause excel -_- t = datetime.strptime(col, '%H:%M').time() except ValueError: err_msg.update({ str(row_idx): 'The end time specified (%s) is not in the correct format' % col }) break school_visit.visit_end = make_aware( datetime.combine(date, t), timezone=request.user.chapter.tz_obj()) if school_visit.visit_end < school_visit.visit_start: err_msg.update({ str(row_idx): 'The end time is earlier than start time' }) break elif colname == 'Location': if col == '': err_msg.update({ str(row_idx): 'You must specify a location for this visit' }) break school_visit.location = col elif colname == 'Visit Type ID': if sint(col) < 0 or sint(col) > 7: stats.visit_type = 0 else: stats.visit_type = sint(col) elif colname == 'Primary Girls First': stats.primary_girls_first = sint(col) elif colname == 'Primary Girls Repeat': stats.primary_girls_repeat = sint(col) elif colname == 'Primary Boys First': stats.primary_boys_first = sint(col) elif colname == 'Primary Boys Repeat': stats.primary_boys_repeat = sint(col) elif colname == 'High Girls First': stats.high_girls_first = sint(col) elif colname == 'High Girls Repeat': stats.high_girls_repeat = sint(col) elif colname == 'High Boys First': stats.high_boys_first = sint(col) elif colname == 'High Boys Repeat': stats.high_boys_repeat = sint(col) elif colname == 'Other Girls First': stats.other_girls_first = sint(col) elif colname == 'Other Girls Repeat': stats.other_girls_repeat = sint(col) elif colname == 'Other Boys First': stats.other_boys_first = sint(col) elif colname == 'Other Boys Repeat': stats.other_boys_repeat = sint(col) elif colname == 'Notes': stats.notes = col else: err_msg.update({ str(row_idx): "Column not recognised, use the column names provided in the template and reupload your file." }) return workshop_list, workshops_imported, err_msg # Only check for existence and save when data is filled correctly if data_filled_correctly: # Perform saves to database d_start = datetime.replace( school_visit.visit_start, microsecond=0, tzinfo=None).__format__('%d/%m/%y %H:%M') d_end = datetime.replace( school_visit.visit_end, microsecond=0, tzinfo=None).time().__format__('%H:%M') try: s = SchoolVisit.objects.get( visit_start=school_visit.visit_start, visit_end=school_visit.visit_end, school=school_visit.school) err_msg.update({ str(row_idx): ' Visit to %s on %s-%s already exists in the database' % (school_visit.school.name, d_start, d_end) }) continue except ObjectDoesNotExist: w = { 'text': { str(row_idx): 'Adding visit to %s on %s-%s' % (school_visit.school.name, d_start, d_end) }, 'attendees': attendees_list } workshop_list.append(w) if save: school_visit.status = 1 school_visit.save() stats.visit = school_visit stats.save() # Save the stats of all attendees for attendee in attendees_list: attendee.event = school_visit attendee.save() err_msg.update(attendee_errors) workshops_imported += 1 return workshop_list, workshops_imported, err_msg