def cleancohortdata(): keywords_to_cohorts = { 'janus' : 'Janus House', 'neptune' : 'Neptune House', 'sol' : 'Sol House', 'health' : 'Health Academy', 'computer' : 'Computer Academy', 'engineering' : 'Engineering Academy', 'fashion' : 'Fashion, Art, and Design Academy', 'race' : 'Race, Policy, and Law Academy', '-----':'No Academy' } blanks = User.objects(cohort = '') blanks.update(cohort = 'No Academy', multi = True) #for student in blanks: # student.update(cohort = 'No Academy') for key in keywords_to_cohorts: group = User.objects(cohort__icontains = key) group.update(cohort = keywords_to_cohorts[key], multi = True) #for student in group: # student.update(cohort = keywords_to_cohorts[key]) # SPED-SDC kids aren't in a cohort, or not in a cohort! SDC_group = User.objects(sped = 'SDC (Special Day Class)', cohort = 'No Academy') SDC_group.update(cohort = 'No Academy - SDC', multi = True) return render_template('index.html')
def addallaeriesTeachers(): settings = Config.objects.first() if settings.devenv == False: flash("You can only run scripts in a local environment.") return redirect('/') # This reads a csv file in to a dataframe df_aeriesteachers = pd.read_csv('csv/aeriesteachers.csv') df_aeriesteachers.fillna('', inplace=True) # This turns that dataframe in to a python dictionary aeriesteachers = df_aeriesteachers.to_dict(orient='records') l = len(aeriesteachers) for index, teacher in enumerate(aeriesteachers): try: otdatateacher = User.objects.get(otemail = teacher['email'].strip()) editTeacher = True except: editTeacher = False if not teacher['teachernum']: teacher['teachernum'] = 0 if editTeacher: otdatateacher.update( taeriesname = teacher['aeriesname'].strip(), tnum = teacher['teachernum'], afname = teacher['fname'].strip(), alname = teacher['lname'].strip(), troom = teacher['room'].strip(), trmphone = teacher['rmphone'].strip(), tdept = teacher['dept'].strip(), role = teacher['title'].strip() ) otdatateacher.reload() else: otdatateacher = User( taeriesname = teacher['aeriesname'], tnum = teacher['teachernum'], afname = teacher['fname'], alname = teacher['lname'], otemail = teacher['email'], troom = teacher['room'], trmphone = teacher['rmphone'], tdept = teacher['dept'], role = teacher['title'] ) otdatateacher.save() print(f"{index}/{l}: {otdatateacher.taeriesname}") return redirect('/')
def findstudent(): students = None form = StudentForm() if form.validate_on_submit(): query3 = Q(role__icontains = 'Student') if form.aeriesid.data: query = Q(aeriesid = form.aeriesid.data) elif len(form.fname.data)>0 and len(form.lname.data)>0: query1 = Q(afname__icontains = form.fname.data) | Q(ufname__icontains = form.fname.data) query2 = Q(alname__icontains = form.lname.data) | Q(ulname__icontains = form.lname.data) query = query1 & query2 & query3 elif len(form.fname.data)>0 and len(form.lname.data)==0: query1 = Q(afname__icontains = form.fname.data) | Q(ufname__icontains = form.fname.data) query = query1 & query3 elif len(form.fname.data)==0 and len(form.lname.data)>0: query2 = Q(alname__icontains = form.lname.data) | Q(ulname__icontains = form.lname.data) query = query2 & query3 else: flash("You didn't enter any names.") return render_template('findstudent.html', form=form) students = User.objects(query) if form.aeriesid.data and len(students) == 0: flash(Markup(f"That ID is not in this database. <a target='_blank' href='https://aeries.ousd.org/Helpers/SetStudentAndRedirect.aspx?ID={form.aeriesid.data}&DU=StudentProfile.aspx'>Check Aeries</a><br> If you get a response that says 'If you are reading this, a redirect did not happen correctly.' it is probably because it is not in Aeries either.")) return render_template('findstudent.html', form=form) elif len(students) == 0: flash("Your search did not find any students.") return render_template('findstudent.html', form=form) return render_template('findstudent.html', form=form, students=students) return render_template('findstudent.html', form=form)
def erasecs(): csstudents = User.objects(cohort__icontains = "computer") total = len(csstudents) for i,stu in enumerate(csstudents): stu.update( cohort = "" ) print(f"{i}:{total}") return redirect('/')
def increasegradebyone(): students = User.objects(role__iexact = 'student') totalstudents = len(students) for i, student in enumerate(students): student.update( grade = student.grade + 1 ) print(f"{i}:{totalstudents}") flash("All Student grades have been increased by 1.") return redirect('/')
def pglist(): stus = User.objects(cohort__icontains='computer', grade__gt=11, postgrads__exists=True) flash(Markup('<b>CS Seniors and alum with PostGrad info --></b>')) for stu in stus: flash( Markup( f'<a href="/profile/{stu.aeriesid}">{stu.fname} {stu.lname} {stu.grade}</a> ({stu.postgrads[0].type_}: {stu.postgrads[0].org})' )) stus = User.objects(cohort__icontains='computer', grade__gt=11, postgrads__exists=False) flash('') flash('') flash('') flash(Markup('<b>CS Seniors and alum with no PostGrad info--></b>')) for stu in stus: flash(f'{stu.fname} {stu.lname} {stu.grade}') return redirect(url_for('index'))
def getcohorts(): allstudents = User.objects().order_by('cohort') temp = '' cohorts = [] for i,stu in enumerate(allstudents): if stu.cohort and not temp == stu.cohort: cohorts.append(stu.cohort) temp = stu.cohort else: temp = stu.cohort flash(cohorts) return render_template('index.html')
def mmcompsci(): mmlist = [[ "Aeries ID", "Student Email", "Grade", "Student fName", "Student lName", "Parent Names", "Parent Emails" ]] csstuds = User.objects(cohort__icontains="computer", grade__lt=13) for csstud in csstuds: stulist = [] anames = None aemails = None stulist.append(csstud.aeriesid) stulist.append(csstud.otemail) stulist.append(csstud.grade) if csstud.ufname and not csstud.ufname == csstud.afname: stulist.append(f"{csstud.afname} ({csstud.ufname})") stulist.append(csstud.alname) else: stulist.append(csstud.afname) stulist.append(csstud.alname) adultisdupe = False adultExists = False if csstud.adults: for adult in csstud.adults: if adult.email: adultExists = True if anames: anames = anames + "zzz" + f" {adult.fname} {adult.lname}" aemails = aemails + "zzz" + adult.email else: anames = f" {adult.fname} {adult.lname}" aemails = adult.email if adult.email.lower() == csstud.aadultemail.lower(): adultisdupe = True if adultisdupe == False: aadults = csstud.aadults.replace(',', '') if anames: if not adultExists: anames = anames + "zzz" + aadults aemails = aemails + "zzz" + csstud.aadultemail else: if not adultExists: anames = aadults aemails = csstud.aadultemail stulist.append(anames) stulist.append(aemails) del anames del aemails mmlist.append(stulist) return render_template('array.html', array=mmlist, nested=True)
def srssmm(): query = Q(cohort__icontains='computer') & Q(grade__gt=11) & Q( shirtsize__exists=False) srs = User.objects(query) seniors = [[ 'Name', 'otemail', 'pemails', 'Shirt Size', 'Personal Email', 'Mobile', 'PostGrad', 'Address' ]] for sr in srs: senior = [] aemails = "" if sr.adults: for adult in sr.adults: if adult.email: aemails += f";{adult.email}" srname = "" senior.append(f"{sr.fname} {sr.lname}") if sr.personalemail: senior.append( f"{sr.otemail};{sr.personalemail},{sr.aadultemail};{aemails}") else: senior.append(f"{sr.otemail},{sr.aadultemail};{aemails}") if not sr.shirtsize: senior.append("No Shirt Size") else: senior.append(sr.shirtsize) if not sr.personalemail: senior.append("No Personal Email") else: senior.append(sr.personalemail) if not sr.mobile: senior.append("No Mobile Phone") else: senior.append(formatphone(sr.mobile)) if not sr.postgrads: senior.append("No PostGrad Info") else: senior.append(f"{sr.postgrads[0].type_}: {sr.postgrads[0].org}") if not sr.ustreet: senior.append("No Address Info") else: senior.append( f"{sr.ustreet} | {sr.ucity} | {sr.ustate} | {sr.uzipcode}") seniors.append(senior) return render_template('array.html', array=seniors, nested=True)
def allpages(): if not session['admin']: flash('You can only see all pages if you are an admin.') return redirect("/") try: pages = Page.objects() except: pages = None try: users = User.objects() except: users = None return render_template('ybookpagesall.html.j2', pages=pages, users=users)
def alladdresses(): students = User.objects(role__iexact="student", grade__lt=13) addresses = [["#", "Street", "City", "State", "Zip", "Cohort"]] for i, student in enumerate(students): address = [ i, student.astreet.replace(',', ''), student.acity, student.astate, student.azipcode ] if student.cohort: address.append(student.cohort.replace(',', '')) else: address.append("None") addresses.append(address) return render_template('array.html', array=addresses, nested=True)
def compsciemails(): emails = [] csstuds = User.objects(cohort__icontains="computer", grade__lt=13) for csstud in csstuds: emails.append(csstud.aadultemail) emails.append(csstud.otemail) emails.append(csstud.personalemail) for adult in csstud.adults: emails.append(adult.email) emails.append(adult.altemail) dedupedemails = list(set(emails)) numdups = len(emails) - len(dedupedemails) flash( Markup( f"I found a total of {numdups} duplicates for a final set of {len(dedupedemails)}" )) return render_template('array.html', array=dedupedemails, nested=False)
def unsetinterventionsfield(): users = User.objects() try: users.update( unset__interventions = 1 ) except Exception as error: print(f"unset Interventions {error}") flash('The Inteventions fields have been removed from all User records. Now delete them from the User data document.') return render_template('index.html') ### Notes on how to create a sandbox // requires mongodb tools on local machine # mongodump --uri mongodb+srv://admin:[email protected]/otdata # change the folder name in the dump directory to otdatasb # C:\Users\steve\OneDrive\Documents\Code\OTData\dump # drop the otdatasb database in Mongodb.com # mongorestore --uri mongodb+srv://admin:[email protected]/otdatasb
def complistall(): usercomps = User.objects(compequiptype__exists=True, compequiptype__ne=None) if len(usercomps) > 0: compslist = [] for user in usercomps: comp = [] comp.append("Student: " + user.fname + " " + user.lname) comp.append(user.compequiptype) comp.append(user.compidnum) comp.append(f"sticker#: {user.compstickernum}") comp.append(f"Date checked out: {user.compdateout}") comp.append(f"Date returned: {user.compdatereturned}") comp.append("Status: " + user.compstatus) comp.append(user.compstatusdesc) compslist.append(comp) else: emptyarray = ["No Computers are Checked out."] return render_template('array.html', array=emptyarray, nested=False) return render_template('array.html', array=compslist, nested=True)
def deleteoldclassnames(): users = User.objects() numusers = len(users) for i,editUser in enumerate(users): if len(editUser.gclasses) > 0: for gclass in editUser.gclasses: try: if gclass.classname == "~": delclassname = True else: delclassname = False except: delclassname = False if delclassname: print(f"{i}:{numusers}: {editUser.id} {editUser.afname}") editUser.gclasses.filter(gclassid=gclass.gclassid).update( classname = None ) editUser.gclasses.filter(gclassid=gclass.gclassid).save() return render_template('index.html')
def fixnames(): users = User.objects() count = len(users) for i,editUser in enumerate(users): if editUser.ufname: fname = editUser.ufname else: fname = editUser.afname if editUser.ulname: lname = editUser.ulname else: lname = editUser.alname if fname != editUser.fname or lname != editUser.lname: editUser.update( fname = fname, lname = lname ) print(f"{i}:{count} Stored new name for {fname} {lname}") return redirect(url_for('index'))
def deletegclassdepricated(): users = User.objects() numusers = len(users) for i,editUser in enumerate(users): if len(editUser.gclasses) > 0: for gclass in editUser.gclasses: try: td = len(gclass.gteacher) except: td = 0 try: cd = len(gclass.gclassdict) except: cd = 0 if td > 0 or cd > 0: print(f"{i}:{numusers}: {editUser.id} {editUser.afname}") editUser.gclasses.filter(gclassid=gclass.gclassid).update( gclassdict = None, gteacher = None ) editUser.gclasses.filter(gclassid=gclass.gclassid).save() return render_template('index.html')
def mailmerge(): query = Q(cohort__icontains='computer') & Q(grade=10) users = User.objects(query) mmlist = [] for user in users: row = [] row.append(f'{user.fname} {user.lname}') emails = f'{user.otemail};{user.aadultemail}' if user.aadultemail: emails += f';{user.aadultemail}' if user.personalemail: emails += f';{user.personalemail}' if user.adults: for adult in user.adults: if adult.email: emails += f';{adult.email}' row.append(emails) mmlist.append(row) print(mmlist) return render_template('array.html', array=mmlist, nested=True)
def aeriesstudentimport(): # TODO: need to add gpa to csv and import script # This reads a csv file in to a dataframe df_aeries = pd.read_csv('csv/aeries.csv', encoding = "ISO-8859-1") df_aeries.fillna('', inplace=True) # This turns that dataframe in to a python dictionary students = df_aeries.to_dict(orient='records') length = len(students) # This iteratates through the students dict for index, student in enumerate(students): # Using the aeriesId as the unique ID, if the Aeries record exists, update all values try: editAeries = User.objects.get(aeriesid = int(student['aeriesid'])) except: editAeries = False if editAeries: editAeries.update( afname = student['afname'], alname = student['alname'], aphone = student['aphone'], azipcode = student['zipcode'], astreet = student['street'], acity = student['city'], astate = student['state'], aadults = student['aadults'], aadultemail = student['adultemail'], aadult1phone = student['adult1phone'], aadult2phone = student['adult2phone'], agender = student['gender'], grade = student['grade'], aethnicity = student['ethnicity'], cohort = student['cohort'], langflu = student['langflu'], sped = student['sped'], gpa = student['gpa'], role = 'student' ) print(f"{index}:{length} {editAeries.otemail} edited") else: # If the Aeries record does not exist, create it using the values in the dictionary newAeries = User( aeriesid = student['aeriesid'], otemail = student['otemail'], afname = student['afname'], alname = student['alname'], aphone = student['aphone'], azipcode = student['zipcode'], astreet = student['street'], acity = student['city'], astate = student['state'], aadults = student['aadults'], aadultemail = student['adultemail'], aadult1phone = student['adult1phone'], aadult2phone = student['adult2phone'], agender = student['gender'], grade = student['grade'], aethnicity = student['ethnicity'], cohort = student['cohort'], langflu = student['langflu'], sped = student['sped'], gpa = student['gpa'], role = 'student' ).save() print(f'{index}:{length} {newAeries.otemail} created') return render_template('index.html')
def compscisrs(): srs=User.objects(cohort__icontains = "computer", grade = 12) return render_template('compscisrs.html',srs=srs)
def login(): # Go and get the users credentials from google. The /authorize and /oauth2callback functions should not be edited. # That is where the user is sent if their credentials are not currently stored in the session. More about sessions below. if 'credentials' not in session: # send a msg to the user # send the user to get authenticated by google return redirect(url_for('authorize')) # Now that the user has credentials, use those credentials to access Google's people api and get the users information credentials = google.oauth2.credentials.Credentials( **session['credentials']) session['credentials'] = credentials_to_dict(credentials) people_service = googleapiclient.discovery.build('people', 'v1', credentials=credentials) # set data to be the dictionary that contains all the information about the user that google has. You can see this # information displayed via the current profile template data = people_service.people().get( resourceName='people/me', personFields='names,emailAddresses,photos').execute() try: issenior = OTSeniors.objects.get( ousdemail=data['emailAddresses'][0]['value']) issenior = True except: issenior = False if data['emailAddresses'][0]['value'][-8:] == "ousd.org" and not data[ 'emailAddresses'][0]['value'][0:2] == "s_": isteacher = True else: isteacher = False if data['emailAddresses'][0]['value'] in admins: isadmin = True else: isadmin = False if not isteacher and not isadmin and not issenior: return redirect(url_for('revoke')) try: # see if the user already exists in the user database document. If they don't then this attempt # to create a currUser object from the User class in the data.py file will fail currUser = User.objects.get( gid=data['emailAddresses'][0]['metadata']['source']['id']) flash(f'Welcome Back! {currUser.fname}') except: # If the user was not in the database, then set some variables and create them # first decide if they are a student or a teacher by checking the front of their email address if data['emailAddresses'][0]['value'][0:2] == 's_': role = 'student' else: role = 'teacher' # Create a newUser object filled with the google values and the values that were just created newUser = User( gid=data['emailAddresses'][0]['metadata']['source']['id'], gfname=data['names'][0]['givenName'], glname=data['names'][0]['familyName'], fname=data['names'][0]['givenName'], lname=data['names'][0]['familyName'], email=data['emailAddresses'][0]['value'], role=role) newUser.save() # Are they a senior if newUser.role == 'student': try: oTSenior = OTSeniors.objects.get(ousdemail=newUser.email) newUser.update(issenior=True, aeriesid=oTSenior.aeriesid) except: pass currUser = User.objects.get(email=newUser.email) flash( f'Welcome {currUser.fname} {currUser.lname}. A New user has been created for you.' ) if currUser.email in admins: if currUser.admin == False: currUser.update(admin=True) else: if currUser.admin == True: currUser.update(admin=False) try: issenior = OTSeniors.objects.get(ousdemail=currUser.email) if currUser.issenior == False: currUser.update(issenior=True, aeriesid=issenior.aeriesid) except: if currUser.issenior == True: currUser.update(issenior=False) session['currUserId'] = str(currUser.id) session['displayName'] = currUser.fname + " " + currUser.lname session['gid'] = currUser.gid # this stores the entire Google Data object in the session session['gdata'] = data session['role'] = currUser.role session['admin'] = currUser.admin session['issenior'] = currUser.issenior # The return_URL value is set above in the before_request route. This enables a user you is redirected to login to # be able to be returned to the page they originally asked for. return redirect(session['return_URL'])
def logins(): logins = User.objects( lastlogin__gt=dt.datetime(2020, 1, 1)).order_by('lastlogin') flash("All Logins.") return render_template('logins.html', logins=logins)
def edits(): edits = User.objects(lastedited__exists=True) flash("Users that have edited their profile") return render_template('edits.html', edits=edits)
def listq(): form = ListQForm() ethnicities = User.objects().distinct(field="aethnicity") ethlist = [] for ethnicity in ethnicities: if len(ethnicity) > 0: ethlist.append((ethnicity, ethnicity)) cohorts = User.objects().distinct(field="cohort") cohortslist = [] for cohort in cohorts: if len(cohort) > 0: cohortslist.append((cohort, cohort)) grades = User.objects().distinct(field="grade") gradeslist = [] for grade in grades: if grade > 0: gradeslist.append((str(grade), str(grade))) genders = User.objects().distinct(field="agender") genderslist = [] for gender in genders: if len(gender) > 0: genderslist.append((gender, gender)) form.cohort.choices = cohortslist form.grade.choices = gradeslist form.ethnicity.choices = ethlist form.gender.choices = genderslist if form.validate_on_submit(): if len(form.cohort.data) > 0: cohortquery = "(" for i, cohort in enumerate(form.cohort.data): cohortquery = cohortquery + f"Q(cohort='{cohort}')" if i < len(form.cohort.data) - 1: cohortquery = cohortquery + ' | ' else: cohortquery = cohortquery + ' ) ' else: cohortquery = '(Q(role__iexact = "student"))' if len(form.ethnicity.data) > 0: ethnicityquery = "(" for i, ethnicity in enumerate(form.ethnicity.data): ethnicityquery = ethnicityquery + f"Q(aethnicity='{ethnicity}')" if i < len(form.ethnicity.data) - 1: ethnicityquery = ethnicityquery + ' | ' else: ethnicityquery = ethnicityquery + ' ) ' else: ethnicityquery = '(Q(role__iexact = "student"))' if len(form.grade.data) > 0: gradequery = "(" for i, grade in enumerate(form.grade.data): gradequery = gradequery + f"Q(grade='{grade}')" if i < len(form.grade.data) - 1: gradequery = gradequery + ' | ' else: gradequery = gradequery + ' ) ' else: gradequery = '(Q(role__iexact = "student"))' if len(form.gender.data) > 0: genderquery = "(" for i, gender in enumerate(form.gender.data): genderquery = genderquery + f"Q(agender='{gender}')" if i < len(form.gender.data) - 1: genderquery = genderquery + ' | ' else: genderquery = genderquery + ' ) ' else: genderquery = '(Q(role__iexact = "student"))' users = User.objects( eval(ethnicityquery) & eval(cohortquery) & eval(gradequery) & eval(genderquery)) return render_template('studentlistform.html', form=form, users=users, total=len(users)) return render_template('studentlistform.html', form=form, users=None, total=None)
def login(): # Go and get the users credentials from google. The /authorize and /oauth2callback functions should not be edited. # That is where the user is sent if their credentials are not currently stored in the session. More about sessions below. if 'credentials' not in session: # send a msg to the user flash('From /login - No credentials in your session. Adding them now.') # send the user to get authenticated by google return redirect(url_for('authorize')) # Now that the user has credentials, use those credentials to access Google's people api and get the users information credentials = google.oauth2.credentials.Credentials(**session['credentials']) session['credentials'] = credentials_to_dict(credentials) people_service = googleapiclient.discovery.build('people', 'v1', credentials=credentials) # set data to be the dictionary that contains all the information about the user that google has. You can see this # information displayed via the current profile template data = people_service.people().get(resourceName='people/me', personFields='names,emailAddresses,photos').execute() # get the google email address from the data object and check to see if the user has an ousd email account. # Deny access if they do not #if not data['emailAddresses'][0]['value'][-8:] == "ousd.org": # flash('You must have an ousd.org email address to access this site') # return redirect(url_for('logout')) try: # see if the user already exists in the user dtabase document. If they don't then this attempt # to create a currUser object from the User class in the data.py file will fail currUser = User.objects.get(gid = data['emailAddresses'][0]['metadata']['source']['id']) flash(f'Welcome Back! {currUser.fname}') # Check the email address in the data object to see if it is in the admins list and update the users # database record if needed. if data['emailAddresses'][0]['value'] in admins: admin = True if currUser.admin == False: currUser.update(admin=True) else: admin = False if currUser.admin == True: currUser.update(admin=False) except: # If the user was not in the database, then set some variables and create them # first decide if they are a student or a teacher by checking the front of their email address if data['emailAddresses'][0]['value'][0:2] == 's_': role = 'student' else: role = 'teacher' #See if the new user is in the Admins list if data['emailAddresses'][0]['value'] in admins: admin = True else: admin = False # Create a newUser object filled with the google values and the values that were just created newUser = User( gid=data['emailAddresses'][0]['metadata']['source']['id'], gfname=data['names'][0]['displayName'], glname=data['names'][0]['familyName'], fname=data['names'][0]['givenName'], lname=data['names'][0]['familyName'], email=data['emailAddresses'][0]['value'], image=data['photos'][0]['url'], role=role, admin=admin ) # save the newUser newUser.save() # then use the mongoengine get() method to get the newUser from the database as the currUser # gid is a unique attribute in the User class that matches google's id which is in the data object currUser = User.objects.get(gid = data['emailAddresses'][0]['metadata']['source']['id']) # send the new user a msg flash(f'Welcome {currUser.fname}. A New user has been created for you.') # this code puts several values in the session list variable. The session variable is a great place # to store values that you want to be able to access while a user is logged in. The values in the sesion # list can be added, changed, deleted as you would with any python list. session['currUserId'] = str(currUser.id) session['displayName'] = currUser.fname+" "+currUser.lname session['gid'] = data['emailAddresses'][0]['metadata']['source']['id'] # this stores the entire Google Data object in the session session['gdata'] = data session['role'] = currUser.role session['admin'] = admin # The return_URL value is set above in the before_request route. This enables a user you is redirected to login to # be able to be returned to the page they originally asked for. return redirect(session['return_URL'])
def profile(aeriesid=None): if aeriesid == 'None': aeriesid = None if session['role'].lower() == "student": targetUser = User.objects.get(id=session['currUserId']) groups = None elif aeriesid and len(aeriesid) < 7: try: targetUser = User.objects.get(aeriesid=aeriesid) except: flash( f"Aeries ID {aeriesid} is not in the database, displaying your profile instead. Contact Steve Wright if you feel this is an error ([email protected])." ) targetUser = User.objects.get(gid=session['gid']) elif aeriesid and len(aeriesid) > 6: try: targetUser = User.objects.get(gid=aeriesid) except: flash( f"The Google ID {aeriesid} is not in the database, displaying your profile instead. Contact Steve Wright if you feel this is an error ([email protected])." ) targetUser = User.objects.get(gid=session['gid']) else: try: targetUser = User.objects.get(gid=session['gid']) except: flash( "You are not in the database of users which doesn't make sense cause you're already looged in. Sorry this shouldn't ever happen. ([email protected])." ) return redirect('/') if targetUser.role.lower() == "student": checkins = CheckIn.objects(student=targetUser).limit(15) else: checkins = None form = CohortForm() cohorts = User.objects().distinct(field="cohort") cohortslist = [("", "None")] for cohort in cohorts: if len(cohort) > 0: cohortslist.append((cohort, cohort)) form.cohort.choices = cohortslist casemanagers = User.objects().distinct(field="casemanager") casemanagerslist = [("", "None")] for casemanager in casemanagers: if len(cohort) > 0: cohortslist.append((casemanager, casemanager)) form.cohort.casemanager = casemanagerslist if form.validate_on_submit(): if len(form.casemanager.data) > 0: targetUser.update(cohort=form.cohort.data, casemanager=form.casemanager.data) else: targetUser.update(cohort=form.cohort.data, unset__casemanager=1) targetUser.reload() form.cohort.data = targetUser.cohort form.casemanager.data = targetUser.casemanager dttoday = dt.datetime.utcnow() if session['role'].lower() != 'student': currUser = User.objects.get(pk=session['currUserId']) groups = Group.objects(owner=currUser) else: groups = None if targetUser.role.lower() == "teacher": sections = Section.objects(teacher=targetUser) else: sections = None return render_template("profile.html", groups=groups, currUser=targetUser, data=session['gdata'], form=form, today=dttoday, checkins=checkins, sections=sections)
def notedits(): query = (Q(lastlogin__gt=dt.datetime(2020, 1, 1)) & Q(role="Student")) & ( Q(lastedited__exists=False) | Q(adults__exists=False)) logins = User.objects(query).order_by('lastedited') flash("Users that have not edited but have logged in") return render_template('logins.html', logins=logins)
def teachers(sort="lname,fname"): teachers = User.objects(role__iexact="teacher") return render_template("coursecat/teachers.html", teachers=teachers, sort=sort)
def compsci(): students = User.objects(cohort__icontains='computer', grade__lt=13).order_by('lastedited') flash("All CompSci Academy students") return render_template('logins.html', logins=students)