def post(self, participant_id, field_slug): participant = self.get_object(participant_id) cf = self.get_custom_field(participant, field_slug) if participant.participant_type == Participant.PARTICIPANT: form_class = ParticipantEditForm else: form_class = MediaParticipantEditForm field_types = [CustomField.IMAGE] Object = custom_object_factory(participant, field_types) Form = custom_form_factory(form_class, field_slugs=[field_slug]) form = Form(obj=Object()) if form.validate(): form.save(participant) cfv = (cf.custom_field_values.filter_by(participant=participant) .scalar()) if cfv: data = get_custom_file_as_filestorage(cfv.value) else: data = {} else: return make_response(jsonify(form.errors), 400) html = render_template('meetings/custom_field/_image_widget.html', data=data) return jsonify(html=html)
def post(self, participant_id, field_slug): participant = self.get_object(participant_id) cf = self.get_custom_field(participant, field_slug) if participant.participant_type == Participant.PARTICIPANT: form_class = ParticipantEditForm g.rule_type = Rule.PARTICIPANT else: form_class = MediaParticipantEditForm g.rule_type = Rule.MEDIA field_types = [CustomField.IMAGE] Object = custom_object_factory(participant, field_types) Form = custom_form_factory(form_class, field_slugs=[field_slug]) form = Form(obj=Object()) if form.validate(): form.save(participant) cfv = (cf.custom_field_values.filter_by( participant=participant).scalar()) if cfv: data = get_custom_file_as_filestorage(cfv.value) else: data = {} else: return make_response(jsonify(form.errors), 400) html = render_template('meetings/custom_field/_image_widget.html', data=data) return jsonify(html=html)
def get(self, participant_id): participant = self._get_queryset(participant_id) Form = custom_form_factory(self.form_class) Object = custom_object_factory(participant) form = Form(obj=Object()) return render_template(self.template, participant=participant, form=form)
def get(self): g.rule_type = Rule.PARTICIPANT search = request.args.get('search', '') Form = custom_form_factory(self.form_class) form = Form() return render_template('meetings/participant/participant/list.html', search=search, form=form)
def test_custom_form_factory(app): pic = ProfilePictureFactory() upload_dir = local(app.config['UPLOADED_CUSTOM_DEST']) upload_dir.ensure(pic.value) g.meeting = pic.participant.meeting field_types = [CustomField.IMAGE] Obj = custom_object_factory(pic.participant, field_types) Form = custom_form_factory(ParticipantEditForm, field_slugs=[pic.custom_field.label.english]) with app.test_request_context(): form = Form(obj=Obj()) assert pic.custom_field.label.english in form._fields
def get(self): queryset = self.get_queryset() participants = search_for_participant(request.args['search'], queryset) results = [] Form = custom_form_factory(self.form_class) for p in participants: Object = custom_object_factory(p) form = Form(obj=Object()) info = self.serialize_participant(form) info['value'] = p.name results.append(info) return json.dumps(results, cls=JSONEncoder)
def get(self): queryset = self.get_queryset() participants = search_for_participant(request.args["search"], queryset) results = [] Form = custom_form_factory(self.form_class) for p in participants: Object = custom_object_factory(p) form = Form(obj=Object()) info = self.serialize_participant(form) info["value"] = p.name results.append(info) return json.dumps(results, cls=JSONEncoder)
def get(self): Form = custom_form_factory(self.form_class, registration_fields=True) form = Form() header_phrase = self.get_header_phrase() footer_phrase = self.get_footer_phrase() if current_user.is_authenticated: participant = self.get_default_participant(current_user) Object = custom_object_factory(participant) form = Form(obj=Object()) return render_template(self.template_name, form=form, header_phrase=header_phrase, footer_phrase=footer_phrase)
def group_participants(cls, participants): start = time.time() participant_form = custom_form_factory(ParticipantEditForm) logger.info("Set participant values, time elapsed: %s", time.time() - start) # Group the participants on two levels: # - the category # - the specified group field of each category. grouped_participants = collections.OrderedDict() for participant in participants: # XXX DO NOT use the custom_object_factory here, as that will trigger # and individual query for each value for each field for each participant # scaling extremely poorly! obj = participant_form(obj=participant) category = participant.category, obj.category_id.render_data( ) or "---" group_key = Category.GROUP_FIELD[participant.category.group.code] try: group_value = (getattr(obj, group_key).label.text, getattr(obj, group_key).render_data() or "---") except AttributeError: group_value = ("", "---") if category not in grouped_participants: grouped_participants[category] = collections.OrderedDict() if group_value not in grouped_participants[category]: grouped_participants[category][group_value] = [] try: # Include the sort field to ensure the sorting order is respected. grouped_participants[category][group_value].append((getattr( obj, participant.category.sort_field.code).render_data() or "---", obj)) except AttributeError: grouped_participants[category][group_value].append( ("---", obj)) logger.info("Grouped participants, time elapsed: %s", time.time() - start) return grouped_participants
def get(self): flag = request.args.get('flag') title = self.TITLE_MAP.get(flag, self.DOC_TITLE) try: categories_ids = map(int, request.args.getlist("category_filter")) except (KeyError, ValueError, TypeError): categories_ids = [] page = int(request.args.get("page", 1)) page_size = int(request.args.get("page_size", self.PAGE_SIZE)) flag_form = FlagForm(request.args) participant_form = custom_form_factory(ParticipantEditForm) all_fields = self._get_all_fields() selected_field_ids = self._get_selected_field_ids() selected_fields = list( participant_form().get_fields(field_ids=selected_field_ids)) with db.session.no_autoflush: grouped_participants, count = self.get_participants( flag=flag, categories_ids=categories_ids, selected_field_ids=selected_field_ids, page=page, page_size=page_size, ) total_pages = int(math.ceil(count / page_size)) return render_template( 'meetings/printouts/provisional_list.html', all_fields=all_fields, selected_field_ids=selected_field_ids, selected_fields=selected_fields, grouped_participants=grouped_participants, count=count, title=title, flag_form=flag_form, flag=flag, page=page, total_pages=total_pages, )
def get(self): registration_token = session.get('registration_token', None) if not registration_token: abort(400) session.pop('registration_token', None) participant = (Participant.query.filter_by( registration_token=registration_token).first_or_404()) if participant.language: set_language(participant.lang) if participant.participant_type == Participant.PARTICIPANT: class_form = ParticipantEditForm g.rule_type = Rule.PARTICIPANT else: class_form = MediaParticipantEditForm g.rule_type = Rule.MEDIA Form = custom_form_factory(class_form) Object = custom_object_factory(participant) form = Form(obj=Object()) return render_template('meetings/registration/user_success.html', form=form)
def post(self): Form = custom_form_factory(self.form_class, registration_fields=True) form = Form(request.form) header_phrase = self.get_header_phrase() footer_phrase = self.get_footer_phrase() if form.validate(): participant = form.save() if current_user.is_authenticated: participant.user = current_user default_participant = self.get_default_participant( current_user) if default_participant: default_participant.update(participant) else: participant.clone() db.session.commit() activity_signal.send(self, participant=participant, action='add') notification_signal.send(self, participant=participant) registration_signal.send(self, participant=participant) email = clean_email(participant.email) user_form = RegistrationUserForm(email=email) session['registration_token'] = participant.registration_token phrases = { 'success_phrase': self.get_success_phrase(), 'user_phrase': self.get_user_phrase(), } return render_template('meetings/registration/success.html', participant=participant, form=user_form, phrases=phrases) return render_template(self.template_name, form=form, header_phrase=header_phrase, footer_phrase=footer_phrase)
def get(self): Form = custom_form_factory(self.form_class) form = Form() return render_template('meetings/participant/media/list.html', form=form)
def get_form(self): return custom_form_factory(self.form_class, excluded_field_types=[CustomField.IMAGE, CustomField.CATEGORY])
def get_form(self): return custom_form_factory( self.form_class, excluded_field_types=[CustomField.IMAGE, CustomField.CATEGORY])
def get(self): Form = custom_form_factory(self.form_class) form = Form() return render_template("meetings/participant/participant/list.html", form=form)
def post(self): if request.files.get("import_file"): try: xlsx = openpyxl.load_workbook(request.files["import_file"], read_only=True) except (zipfile.BadZipfile, InvalidFileException) as e: flash("Invalid XLS file: %s" % e, 'danger') context = { "participant_type": self.participant_type, } return render_template('meetings/participant/import/list.html', **context) request.files["import_file"].seek(0) file_name = str(uuid.uuid4()) + '.xlsx' # Save the file so we only upload it once. request.files["import_file"].save( app.config['UPLOADED_PRINTOUTS_DEST'] / file_name) else: file_name = request.form["file_name"] try: xlsx = openpyxl.load_workbook( app.config['UPLOADED_PRINTOUTS_DEST'] / file_name, read_only=True) except (zipfile.BadZipfile, InvalidFileException) as e: flash("Invalid XLS file: %s" % e, 'danger') context = { "participant_type": self.participant_type, } return render_template('meetings/participant/import/list.html', **context) custom_fields = (g.meeting.custom_fields.filter_by( custom_field_type=self.participant_type).order_by( CustomField.sort)) custom_fields = [ field for field in custom_fields if field.field_type.code != CustomField.EVENT ] has_errors = False try: rows = list(read_sheet(xlsx, custom_fields)) assert rows, "file has no data" except (AssertionError, ValueError) as e: flash("Invalid XLS file: %s" % e, 'danger') context = { "participant_type": self.participant_type, } return render_template('meetings/participant/import/list.html', **context) forms = [] for form in read_participants_excel(custom_fields, rows, self.form_class): has_errors = not form.validate() or has_errors forms.append(form) all_fields = list( custom_form_factory(self.form_class)().exclude([ CustomField.EVENT, ])) context = { "forms": forms, "has_errors": has_errors, "all_fields": all_fields, "file_name": file_name, "participant_type": self.participant_type, } if has_errors: flash( 'XLS file has errors, please review and correct them and try again. ' 'Hover over cells to find more about the errors.', 'danger') elif request.form["action"] == "import": _add_to_printout_queue(_process_import_participants_excel, self.JOB_NAME, rows, self.participant_type, self.form_class) context["import_started"] = True else: flash( 'XLS file is valid, please review and hit "Start import" after.', 'success', ) return render_template('meetings/participant/import/list.html', **context)
def read_participants_excel(custom_fields, rows, form_class, read_files=False): meeting_categories = {} for c in Category.get_categories_for_meeting( form_class.CUSTOM_FIELDS_TYPE): meeting_categories[c.title.english.lower()] = c.id countries = {} for code, name in get_all_countries(): countries[name.lower()] = code custom_fields = { custom_field.slug: custom_field for custom_field in custom_fields } Form = custom_form_factory(form_class) for row_num, row in enumerate(rows, start=2): participant_details = [] for slug, value in row.items(): value = value.strip() if not value: continue custom_field = custom_fields[slug] field_type = custom_field.field_type.code if field_type == CustomField.CATEGORY: value = meeting_categories.get(unicode(value).lower(), -1) elif field_type == CustomField.COUNTRY: value = countries.get(value.lower(), "invalid-country") elif field_type == CustomField.MULTI_CHECKBOX: value = [el.strip() for el in value.split(",")] elif field_type in (CustomField.IMAGE, CustomField.DOCUMENT): if read_files: resp = requests.get(value, stream=True) resp.raise_for_status() content_type = resp.headers.get( 'content-type', 'application/octet-stream') content_length = resp.headers.get('content-length', None) filename = parse_rfc6266_header( resp.headers.get("content-disposition", "")).get("filename") if not filename: # Attempt to guess the extension of the file ext = mimetypes.guess_extension(content_type) if ext: filename = str(uuid.uuid4()) + ext value = FileStorage( stream=io.BytesIO(resp.content), filename=filename, content_type=content_type, content_length=content_length, headers=resp.headers, ) else: # TODO: Add some form of validation to check the URLs are valid # A HEAD request could also be done in theory fast enough. pass if isinstance(value, list): # Multi checkbox values for val in value: participant_details.append((slug, val)) else: participant_details.append((slug, value)) form = Form(formdata=ImmutableMultiDict(participant_details), read_from_request=False) form.excel_row = row_num # Set the original value so the frontend can present it as such. for slug, value in row.items(): form[slug].excel_value = value.strip() yield form
def _get_all_fields(): """Get all displayable fields for this meeting.""" participant_form = custom_form_factory(ParticipantEditForm) return list(participant_form().exclude( [CustomField.CHECKBOX, CustomField.IMAGE, CustomField.EVENT]))