def person_slug(): firstname = request.form.get('firstname') lastname = request.form.get('lastname') fullname = request.form.get('fullname') slug = Person.make_slug(firstname, lastname, fullname) resp = { "firstname": firstname, "lastname": lastname, "fullname": fullname, "slug": slug, } return jsonify(resp)
def add_person(row): birth_date = parse_datetime(row['birth_date'], DATE_FORMAT) if birth_date is not None: birth_date = birth_date.date() phone_number = parse_phone_number(row['phone_number']) if phone_number == '': phone_number = None email = row['email'] if email == '': email = None person = Person( surname = row['surname'], name = row['name'], father_name = row['father_name'], birth_date = birth_date, vk_id = get_numeric_id(row['vk_id']), phone_number = phone_number, email = email ) person.save() return person
def add_person(): person = Person() form = PersonForm() if form.validate_on_submit(): form.populate_obj(person) db.session.add(person) db.session.commit() flash(gettext("Your changes have been saved.")) return redirect(url_for('view_person', slug=person.slug)) return render_template( 'person/edit.html', form=form, )
def get_person(row): birth_date = parse_datetime(row['birth_date'], DATE_FORMAT) if birth_date is not None: birth_date = birth_date.date() return Person.get_by_match( surname = row['surname'], name = row['name'], father_name = row['father_name'], birth_date = birth_date, vk_id = get_numeric_id(row['vk_id']), phone_number = parse_phone_number(row['phone_number']), email = row['email'] )
def add_person(sciper): """Add the person to the database Args: sciper (str): the sciper of the person to be added Returns: Person: The created entry in DB """ logger.info("adding person with sciper #" + sciper) ldapData = get_users(settings, [sciper])[0] person = Person() person.sciper = sciper person.username = ldapData["username"] person.email = ldapData["email"] person.first_name = ldapData["first_name"] person.last_name = ldapData["last_name"] person.save() return person
def get_new_phds(): logger.info("Retrieving all TAs from LDAP") phd_group = Group.objects.get(name="phds") TAs = epfl_ldap.get_STI_TA_Students(settings) for key, TA in TAs.items(): try: TA_obj = Person.objects.get(sciper=TA["sciper"]) logger.debug("found entry for sciper {}".format(TA["sciper"])) except Person.DoesNotExist: logger.info("creating user for sciper {}".format(TA["sciper"])) TA_obj = Person() TA_obj.sciper = TA["sciper"] TA_obj.username = TA["username"] TA_obj.first_name = TA["first_name"] TA_obj.last_name = TA["last_name"] TA_obj.email = TA["mail"] TA_obj.save() TA_obj.groups.add(phd_group)
def view_person(slug=None): if slug is None: person = None else: person = Person.by_slug(slug) page = 1 # movies = Movie.by_director(person, order_by=session.get('sort_by')).paginate(page, app.config.get('BRIEF_MOVIES_PER_PAGE', 6), False) movies = person.directed.paginate( page, app.config.get('BRIEF_MOVIES_PER_PAGE', 6), False) print("Directed", person.directed) return render_template( 'person/view.html', person=person, movies=movies, slug=slug, )
def load_teachers(teachers=list()): logger.info("loading teachers") logger.debug("teachers: %s", teachers) teachers_group = Group.objects.get(name="teachers") return_value = list() if not os.path.isfile(settings.PICKLED_DATA_FROM_LDAP): load_mappings() pickle_in = open(settings.PICKLED_DATA_FROM_LDAP, 'rb') mappings = pickle.load(pickle_in) for teacher in teachers: if teacher in mappings: base_data = mappings[teacher] try: existing_user = Person.objects.get(sciper=base_data['sciper']) # Make sure that the teacher belongs to the teachers group if not existing_user.groups.filter(name="teachers").exists(): teachers_group.user_set.add(existing_user) return_value.append(existing_user) except ObjectDoesNotExist as ex: new_person = Person() new_person.sciper = base_data['sciper'] new_person.username = base_data['username'] if 'mail' in base_data: new_person.email = base_data['mail'] new_person.first_name = base_data['first_name'] new_person.last_name = base_data['last_name'] new_person.save() # Add the teacher to the teachers group for later use teachers_group.user_set.add(new_person) return_value.append(new_person) return return_value
class MovieForm(FlaskForm): title = TextField(gettext('Title'), validators=[Required(), ]) original_title = TextField(gettext('Original title')) slug = TextField(gettext('URL'), validators=[ Required(), Length(min=1, max=64), Regexp("[a-zA-Z0-9_\-]*"), ]) wiki_url = TextField(gettext('Wiki')) genre_ids = FieldList(QuerySelectField(gettext('Genre'), get_label='title', query_factory=lambda: Genre.alphabet(), allow_blank=True), min_entries=1) director_ids = FieldList(QuerySelectField(gettext('Director'), get_label=lambda p: p.get_name(), query_factory=lambda: Person.alphabet(), allow_blank=True), min_entries=1) image = HiddenField() description = TextAreaField(gettext('Description')) def applyGenres(self, genres): if genres.count(): while len(self.genre_ids) > 0: self.genre_ids.pop_entry() for genre in genres: self.genre_ids.append_entry(genre) def applyDirectors(self, directors): print("APPLY DIRECTORS", directors.all()) if directors.count(): while len(self.director_ids) > 0: self.director_ids.pop_entry() for director in directors: self.director_ids.append_entry(director)
def load_teacher(row): logger.info("loading teacher") logger.debug(row["sciper"]) sciper = row["sciper"] if pd.isnull(sciper): logger.warning("Teacher not added because the sciper is null") return try: teacher = Person.objects.get(sciper=sciper) except ObjectDoesNotExist: teacher = Person() teacher.sciper = row["sciper"] teacher.username = get_username(row["sciper"]) teacher.first_name = get_firstname(row["sciper"]) teacher.last_name = get_lastname(row["sciper"]) teacher.email = get_email(row["sciper"]) if ( pd.isnull(teacher.first_name) or pd.isnull(teacher.last_name) or pd.isnull(teacher.email) ): logger.warning( "teacher not saved because he does not have a first name or a last name or an email address" ) return else: logger.debug("saving teacher") teacher.save() teachers_group = Group.objects.get(name="teachers") if teacher.groups.filter(name="teachers").exists() == False: logger.debug("adding teacher to group") teachers_group.user_set.add(teacher) teachers_group.save() teacher.save() else: logger.debug("teacher already part of the group")
def req_list(req): user = cur_user() if user is None or user.get_status() not in ACCESS_GROUP: return redirect(url_for('low_access_level', req_access='m')) if req == 'persons': filter_form = PersonsFilterForm() if filter_form.validate_on_submit(): if filter_form.id.data is not None: persons = Person.get(id=filter_form.id.data) if persons is not None: persons = [persons] else: persons = [ p for p in Person.get_partly(filter_form.full_name.data) ] if filter_form.is_student.data: t = [p for p in persons if p.student] persons = t if filter_form.is_teacher.data: t = [p for p in persons if p.teacher] persons = t else: persons = Person.get_all() return render_template('study/lists/persons_list.html', title='Список физ. лиц', user=user, persons=persons, form=filter_form) if req == 'students': filter_form = StudentsFilterForm() if filter_form.validate_on_submit(): if filter_form.id.data is not None: students = Student.get(id=filter_form.id.data) if students is not None: students = [students] else: students = [ p.student for p in Person.get_partly(filter_form.full_name.data) if p.student ] if filter_form.group.data != 0: t = [ s for s in students if s.group.id == filter_form.group.data ] students = t if filter_form.department.data != 0: t = [ s for s in students if s.group.department.id == filter_form.department.data ] students = t elif filter_form.edu_org.data != 0: t = [ s for s in students if s.group.department.edu_org.id == filter_form.edu_org.data ] students = t else: students = Student.get_all() return render_template('study/lists/students_list.html', title='Список обучающихся', user=user, students=students, form=filter_form, load_js=['filter_departments', 'filter_groups']) if req == 'teachers': filter_form = TeachersFilterForm() if filter_form.validate_on_submit(): if filter_form.id.data is not None: teachers = Teacher.get(id=filter_form.id.data) if teachers is not None: teachers = [teachers] else: teachers = [ p.teacher for p in Person.get_partly(filter_form.full_name.data) if p.teacher ] if filter_form.subject.data != 0: subject_name = Subject.get( id=filter_form.subject.data).name t = [ teacher for teacher in teachers if len(teacher.get_subject_by_part(name=subject_name)) ] teachers = t if filter_form.department.data != 0: t = [ teacher for teacher in teachers if teacher.department.id == filter_form.department.data ] teachers = t elif filter_form.edu_org.data != 0: t = [ teacher for teacher in teachers if teacher.department.edu_org.id == filter_form.edu_org.data ] teachers = t else: teachers = Teacher.get_all() return render_template('study/lists/teachers_list.html', title='Список преподавателей', user=user, teachers=teachers, form=filter_form, load_js=['filter_departments']) if req == 'edu_orgs': edu_orgs = EducationalOrganization.get_all() return render_template('study/lists/edu_orgs_list.html', title='Список учреждений', user=user, edu_orgs=edu_orgs) if req == 'departments': departments = Department.get_all() return render_template('study/lists/departments_list.html', title='Список подразделений', user=user, departments=departments) return redirect(url_for('main'))
def parse(request, documentPk): document = Document.objects.get(pk=documentPk) categories = Category.objects.all() runs = Run.objects.all() persons = Person.objects.all() results = Result.objects.all() xmlParser = Parser('/home/django/django_project' + document.xmlfile.url).select_parser() newRun = Run(name=xmlParser.event_data.get('name','NEPOMENOVANY BEH').strip(), date=xmlParser.event_data.get('date','1700-01-01' ), season=document.season) runAlreadyInDatabase = False for everyRun in runs: if everyRun.season == newRun.season and everyRun.name == newRun.name and str(everyRun.date) == newRun.date: runAlreadyInDatabase = True runInXML = everyRun break if runAlreadyInDatabase == False: runInXML = newRun newRun.save() for key in xmlParser.runners_data.keys(): categoryAlreadyInDatabase = False tmpCat = Category(name=key.strip()) for runnerCategory in categories: if tmpCat.name == runnerCategory.name: categoryAlreadyInDatabase = True break if categoryAlreadyInDatabase == False: tmpCat.save() for xmlPerson in xmlParser.runners_data[key]: try: newClub = Club.objects.get(name=unicode(xmlPerson.get('club','N/A')).strip()) except Club.DoesNotExist: newClub = Club(name=unicode(xmlPerson.get('club','N/A')).strip()) newClub.save() newPerson = Person(first_name = xmlPerson['meno'].strip(), last_name = xmlPerson['priezvisko'].strip(), category = Category.objects.get(name=key.strip()), club= Club.objects.get(name=unicode(xmlPerson.get('club','N/A')).strip())) newPerson.ccard=xmlPerson.get('ccard',0) newPerson.person_id=xmlPerson.get('person_id',"0") if len(newPerson.person_id) >= 3: for club in Club.objects.all(): pass if newPerson.ccard is None: newPerson.ccard = 0 personAlreadyInDatabase = False for everyPerson in persons: if newPerson.first_name == everyPerson.first_name and newPerson.last_name == everyPerson.last_name and newPerson.category == everyPerson.category: personAlreadyInDatabase = True personInXML = everyPerson break if personAlreadyInDatabase == False: personInXML = newPerson newPerson.save() newRes = Result(person=Person.objects.get(pk=personInXML.pk), run=Run.objects.get(pk=runInXML.pk),start_time=xmlPerson.get('starttime','00:00:00'),finish_time=xmlPerson.get('finishtime','00:00:00'), status=xmlPerson['status'], points=Decimal("0"), position_run=xmlPerson.get('position',0)) result_time=xmlPerson.get('time','00:00:00') if result_time.count(":") == 1: result_time = "00:" + result_time if result_time.count(":") > 0: time = result_time.encode('ascii', 'ignore') result_time = timeSum(time) newRes.result_time = result_time resultAlreadyInDatabase = False for everyResult in results: if personInXML == everyResult.person and runInXML == everyResult.run: resultAlreadyInDatabase = True break if resultAlreadyInDatabase == False: newRes.save() return HttpResponseRedirect(reverse('web:databasePerson'))
def merge(request): data = pickle.loads(request.session['data']) model = pickle.loads(request.session['model']) if request.method == "POST": if str(model) == 'club': form = ClubForm(request.POST) if form.is_valid(): newClub = Club(name = request.POST['name']) newClub.save() clubsToChange = Club.objects.filter(pk__in = data) runnersToChange = Person.objects.filter(club__in = clubsToChange) for runner in runnersToChange: runner.club = newClub runner.save() #deleting clubs which are now obsolete for club in clubsToChange: club.delete() return HttpResponseRedirect(reverse('admin:index')) elif str(model) == 'category': form = CategoryForm(request.POST) if form.is_valid(): newCategory = Category(name = request.POST['name']) newCategory.save() categoriesToChange = Category.objects.filter(pk__in = data) runnersToChange = Person.objects.filter(category__in = categoriesToChange) for runner in runnersToChange: runner.category = newCategory runner.save() #deleting categories which are now obsolete for category in categoriesToChange: category.delete() return HttpResponseRedirect(reverse('admin:index')) elif str(model) == 'person': form = PersonForm(request.POST) if form.is_valid(): newPerson = Person(first_name = request.POST['first_name'],last_name = request.POST['last_name'],category = Category.objects.get(pk=request.POST['category']),person_id = request.POST['person_id'],club= Club.objects.get(pk=request.POST['club']),ccard = request.POST['ccard']) newPerson.save() runnersToChange = Person.objects.filter(pk__in = data) for oldRunner in runnersToChange: for oldRunnerRun in oldRunner.runs.all(): oldResult = Result.objects.get(person=oldRunner.pk,run = oldRunnerRun.pk) renewResult = oldResult renewResult.person = newPerson renewResult.save() #deleting categories which are now obsolete for runner in runnersToChange: runner.delete() return HttpResponseRedirect(reverse('admin:index')) return HttpResponseRedirect(reverse('web:index')) else: if str(model) == 'club': zoznam = Club.objects.filter(pk__in = data) form = ClubForm(initial={'name':zoznam[0].name, 'shortcut':zoznam[0].shortcut}) elif str(model) == 'person': zoznam = Person.objects.filter(pk__in = data) form = PersonForm(initial={'first_name':zoznam[0].first_name,'last_name':zoznam[0].last_name, 'person_id':zoznam[0].person_id, 'club':zoznam[0].club, 'ccard':zoznam[0].ccard, 'category':zoznam[0].category}) elif str(model) == 'category': zoznam = Category.objects.filter(pk__in = data) form = CategoryForm(initial={'name':zoznam[0].name}) return render(request, 'web/merge.html', {'form':form, 'zoznam':zoznam, })
def load_teacher(sciper): logger.info("loading teacher") logger.debug(sciper) try: teacher = Person.objects.get(sciper=sciper) except ObjectDoesNotExist: teacher = Person() teacher.sciper = sciper teacher.username = get_username(sciper) teacher.first_name = get_firstname(sciper) teacher.last_name = get_lastname(sciper) teacher.email = get_email(sciper) if ( teacher.first_name is None or teacher.last_name is None or teacher.email is None ): logger.warning( "teacher not saved because he does not have a first name or a last name or an email address" ) return "teacher not saved because he does not have a first name or a last name or an email address" else: logger.debug("saving teacher") teacher.save() teachers_group = Group.objects.get(name="teachers") if teacher.groups.filter(name="teachers").exists() == False: logger.debug("adding teacher to group") teachers_group.user_set.add(teacher) teachers_group.save() teacher.save() else: logger.debug("teacher already part of the group") return ""