예제 #1
0
)

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://"  # Use in-memory database
app.debug = True
db = SQLAlchemy(app)

QueryRadioField = partial(
    QuerySelectField,
    widget=widgets.ListWidget(prefix_label=False),
    option_widget=widgets.RadioInput(),
)
QueryCheckboxField = partial(
    QuerySelectMultipleField,
    widget=widgets.ListWidget(prefix_label=False),
    option_widget=widgets.CheckboxInput(),
)


class Continent(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)

    def __repr__(self):
        return self.name

    def __str__(self):
        return self.name

    def __init__(self, name):
        self.name = name
예제 #2
0
class AddEntryForm(FlaskForm):
    """Add new session entry form"""
    date = DateField("Date",validators=[InputRequired()])
    therapist = QuerySelectField('Therapist',query_factory=lambda: Therapist.query.all(), allow_blank = False, get_label='full_name')
    nrs1 = IntegerRangeField("NRS1", validators=[InputRequired(), NumberRange(min=0, max=100)])
    nrs2 = IntegerRangeField("NRS2", validators=[InputRequired(), NumberRange(min=0, max=100)])
    nrs3 = IntegerRangeField("NRS3", validators=[InputRequired(), NumberRange(min=0, max=100)])
    nrs4 = IntegerRangeField("NRS4", validators=[InputRequired(), NumberRange(min=0, max=100)])
    nrs5 = IntegerRangeField("NRS5", validators=[InputRequired(), NumberRange(min=0, max=100)])
    a_event = TextAreaField("A: Adversity/ Activating Event: Now that you've checked in with yourself, what would you like to start with today?", validators=[InputRequired()])
    beliefs = TextAreaField("Beliefs (About this Adversity):", validators=[InputRequired()])
    c_distortions = SelectMultipleField('Cognitive Distortions', choices=[('All-or-Nothing Thinking / Polarized Thinking','All-or-Nothing Thinking / Polarized Thinking'),('Awfulizing, Catastrophizing','Awfulizing, Catastrophizing'),('Overgeneralization','Overgeneralization'),('Mental Filter','Mental Filter'),('Disqualifying the Positive','Disqualifying the Positive'),('Jumping to Conclusions – Mind Reading', 'Jumping to Conclusions – Mind Reading'),('Jumping to Conclusions – Fortune Telling', 'Jumping to Conclusions – Fortune Telling'),('Magnification (Catastrophizing) or Minimization','Magnification (Catastrophizing) or Minimization'),('Emotional Reasoning', 'Emotional Reasoning'),('Should Statements', 'Should Statements'),('Labeling and Mislabeling', 'Labeling and Mislabeling'),('Personalization', 'Personalization'),('Control Fallacies','Control Fallacies'),('Fallacy of Fairness', 'Fallacy of Fairness'),('Fallacy of Change', 'Fallacy of Change'),('Always Being Right', 'Always Being Right'),('If/Then, Non-sequitur', 'If/Then, Non-sequitur')], option_widget=widgets.CheckboxInput(), widget=widgets.ListWidget(prefix_label=False))
    c_consequences = SelectMultipleField('C: Consequences: Emotional- Unhealthy Negative Emotions Identified', choices=[('Anger','Anger'),('Anxiety','Anxiety'),('Depression','Depression'),('Guilt','Guilt'),('Shame','Shame'),('Resentment','Resentment'),('Jealousy','Jealousy'),('Panic','Panic')], option_widget=widgets.CheckboxInput(), widget=widgets.ListWidget(prefix_label=False))
    reactions = TextAreaField("C- Consequences: Behaviors & Reactions", validators=[InputRequired()])
class MultiCheckboxField(SelectMultipleField):
    widget = TableColWidget(with_table_tag=False)
    option_widget = widgets.CheckboxInput()
예제 #4
0
class MultiCheckboxField(SelectMultipleField):
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()

    def pre_validate(self, form):
        """per_validation is disabled"""
예제 #5
0
파일: forms.py 프로젝트: Nekson228/Webby
class MultiCheckboxField(SelectMultipleField):
    """Класс кастомного поля со множеством чекбоксов."""
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
예제 #6
0
class JournalInformation(Form):
    """All the bibliographic metadata associated with a journal in the DOAJ"""

    title = StringField('Journal Title', [validators.DataRequired()])
    url = URLField('URL', [validators.DataRequired(), URLOptionalScheme()])
    alternative_title = StringField('Alternative Title',
                                    [validators.Optional()])
    pissn = StringField(
        'Journal ISSN (print version)',
        [
            OptionalIf('eissn'),
            validators.Regexp(regex=ISSN_REGEX, message=ISSN_ERROR)
        ],
        description=
        'Only provide the print ISSN if your journal has one, otherwise leave this field blank. Write the ISSN with the hyphen "-" e.g. 1234-4321.',
    )
    eissn = StringField(
        'Journal ISSN (online version)',
        [
            OptionalIf('pissn'),
            validators.Regexp(regex=ISSN_REGEX, message=ISSN_ERROR)
        ],
        description=
        'Cannot be the same as the P-ISSN. Write the EISSN with the hyphen "-" e.g. 1234-4321.',
    )
    publisher = StringField('Publisher', [validators.DataRequired()])
    society_institution = StringField(
        'Society or Institution',
        [validators.Optional()],
        description=
        'The name of the Society or Institution that the journal belongs to.',
    )
    platform = StringField(
        'Platform, Host or Aggregator', [validators.Optional()],
        description=
        'The name of the platform, host or aggregator of the journal content, e.g. OJS, HighWire Press, EBSCO etc.'
    )
    contact_name = StringField(
        'Name of contact for this journal',
        [validators.DataRequired()],
        description='Somebody who DOAJ can contact about this journal.',
    )
    contact_email = StringField('Contact\'s email address', [
        validators.DataRequired(),
        validators.Email(message='Invalid email address.')
    ])
    confirm_contact_email = StringField('Confirm contact\'s email address', [
        validators.DataRequired(),
        validators.Email(message='Invalid email address.'),
        validators.EqualTo('contact_email', EMAIL_CONFIRM_ERROR)
    ])
    country = DOAJSelectField(
        'In which country is the publisher of the journal based?',
        [validators.DataRequired()],
        description=
        'Select the country where the publishing company carries out its business activities. Addresses registered via a registered agent are not allowed.',
        choices=Choices.country(),
    )
    processing_charges = RadioField(
        'Does the journal have article processing charges (APCs)?',
        [validators.DataRequired()],
        # description = 'If "No" proceed to question below',
        choices=Choices.processing_charges())
    processing_charges_url = URLField(
        'Enter the URL where this information can be found',
        [validators.DataRequired(),
         URLOptionalScheme()],
        # description='This field is optional if you have selected "No" above'
    )
    processing_charges_amount = IntegerField(
        'Amount',
        [
            OptionalIf('processing_charges',
                       optvals=Choices.processing_charges_amount_optional())
        ],
    )
    processing_charges_currency = DOAJSelectField('Currency', [
        OptionalIf('processing_charges',
                   optvals=Choices.processing_charges_currency_optional())
    ],
                                                  choices=Choices.currency())

    submission_charges = RadioField(
        'Does the journal have article submission charges?',
        [validators.DataRequired()],
        # description = 'If "No" proceed to question below',
        choices=Choices.submission_charges())
    submission_charges_url = URLField(
        'Enter the URL where this information can be found',
        [validators.DataRequired(),
         URLOptionalScheme()],
        # description='This field is optional if you have selected "No" above'
    )
    submission_charges_amount = IntegerField(
        'Amount',
        [
            OptionalIf('submission_charges',
                       optvals=Choices.submission_charges_amount_optional())
        ],
    )
    submission_charges_currency = DOAJSelectField('Currency', [
        OptionalIf('submission_charges',
                   optvals=Choices.submission_charges_amount_optional())
    ],
                                                  choices=Choices.currency())
    waiver_policy = RadioField(
        'Does the journal have a waiver policy (for developing country authors etc)?',
        [validators.DataRequired()],
        choices=Choices.waiver_policy())
    waiver_policy_url = URLField(
        'Enter the URL where this information can be found', [
            OptionalIf('waiver_policy',
                       optvals=Choices.waiver_policy_url_optional()),
            URLOptionalScheme()
        ])
    digital_archiving_policy = DOAJSelectMultipleField(
        'What digital archiving policy does the journal use?', [
            validators.DataRequired(),
            ExclusiveCheckbox(Choices.digital_archiving_policy_val("none")),
            ExtraFieldRequiredIf(
                'digital_archiving_policy_library',
                reqval=Choices.digital_archiving_policy_val("library")),
            ExtraFieldRequiredIf(
                'digital_archiving_policy_other',
                reqval=Choices.digital_archiving_policy_val("other")),
        ],
        description=
        "Select all that apply. Institutional archives and publishers' own online archives are not valid.",
        choices=Choices.digital_archiving_policy(),
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False))
    digital_archiving_policy_other = StringField(
        'Digital Archiving Policy (Other)', )
    digital_archiving_policy_library = StringField(
        'Digital Archiving Policy (Library)', )
    digital_archiving_policy_url = URLField(
        'Enter the URL where this information can be found',
        [
            OptionalIf(
                'digital_archiving_policy',
                optvals=Choices.digital_archiving_policy_url_optional()),
            URLOptionalScheme()
        ],
        description=
        'This field is optional if you selected "No policy in place".',
    )
    crawl_permission = RadioField(
        'Does the journal allow software/spiders to automatically crawl the journal content (also known as text mining)?',
        [validators.DataRequired()],
        choices=Choices.crawl_permission())
    article_identifiers = DOAJSelectMultipleField(
        'Which article identifiers does the journal use?',
        [
            validators.DataRequired(),
            ExtraFieldRequiredIf(
                'article_identifiers_other',
                reqval=Choices.article_identifiers_val("other")),
            ExclusiveCheckbox()
        ],
        choices=Choices.article_identifiers(),
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False),
    )
    article_identifiers_other = StringField('Article Identifiers (Other)', )
    download_statistics = RadioField(
        'Does the journal provide article download statistics?',
        [validators.DataRequired()],
        description='If "No" proceed to question 32.',
        choices=Choices.download_statistics())
    download_statistics_url = StringField(
        'Enter the URL where this information can be found',
        [validators.Optional(), URLOptionalScheme()],
    )
    first_fulltext_oa_year = IntegerField(
        'What was the first calendar year in which a complete volume of the journal provided online Open Access content to the Full Text of all articles? (Full Text may be provided as PDFs. Does not apply for new journals.)',
        [
            validators.DataRequired(),
            validators.NumberRange(min=1600, max=(datetime.now().year))
        ],
        description='Use 4 digits for the year, i.e. YYYY format.')
    fulltext_format = DOAJSelectMultipleField(
        'Please indicate which formats of full text are available', [
            validators.DataRequired(),
            ExtraFieldRequiredIf('fulltext_format_other',
                                 reqval=Choices.fulltext_format_val("other"))
        ],
        description='Tick all that apply.',
        choices=Choices.fulltext_format(),
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False))
    fulltext_format_other = StringField('Fulltext Format (Other)', )
    keywords = TagListField(
        'Add keyword(s) that best describe the journal (comma delimited)', [
            validators.DataRequired(),
            MaxLen(6, message='You can only enter up to {max_len} keywords.')
        ],
        description='Maximum 6. Keywords must be in English.')
    languages = DOAJSelectMultipleField(
        'Select the language(s) that the Full Text of the articles is published in',
        [validators.DataRequired()],
        choices=Choices.language(),
        description="You can select multiple languages.")
    editorial_board_url = URLField(
        'What is the URL for the Editorial Board page?',
        [validators.DataRequired(),
         URLOptionalScheme()],
        description=
        'A journal must have an editor and an editorial board. Only in the case of Arts and Humanities journals we will accept a form of editorial review using only two editors and no editorial board. Where an editorial board is present, members must be clearly identifiable with their names and affiliation information.'
    )
    review_process = DOAJSelectField(
        'Please select the review process for papers',
        [validators.DataRequired()],
        choices=Choices.review_process(),
        default=Choices.review_process_default(),
    )
    review_process_url = URLField(
        'Enter the URL where this information can be found', [
            OptionalIf('review_process',
                       optvals=Choices.review_process_url_optional()),
            URLOptionalScheme()
        ],
        description='This field is optional if you have selected "None" above.'
    )
    aims_scope_url = URLField("What is the URL for the journal's Aims & Scope",
                              [validators.DataRequired(),
                               URLOptionalScheme()])
    instructions_authors_url = URLField(
        "What is the URL for the journal's instructions for authors?",
        [validators.DataRequired(),
         URLOptionalScheme()])
    plagiarism_screening = RadioField(
        'Does the journal have a policy of screening for plagiarism?',
        [validators.DataRequired()],
        description='If "No" proceed to question 43.',
        choices=Choices.plagiarism_screening())
    plagiarism_screening_url = URLField(
        "Enter the URL where this information can be found", [
            OptionalIf('plagiarism_screening',
                       optvals=Choices.plagiarism_screening_url_optional()),
            URLOptionalScheme()
        ],
        description=
        "The URL should state that the journal actively checks for plagiarism and detail how this is done."
    )
    publication_time = IntegerField(
        'What is the average number of weeks between submission and publication?',
        [validators.DataRequired(),
         validators.NumberRange(min=0, max=53)])
    oa_statement_url = URLField(
        "What is the URL for the journal's Open Access statement?",
        [validators.DataRequired(),
         URLOptionalScheme()])
    license_embedded = RadioField(
        'Does the journal embed or display licensing information in its articles?',
        [validators.DataRequired()],
        choices=Choices.licence_embedded(),
        description=
        'For more information go to <a target="_blank" href="http://wiki.creativecommons.org/CC_REL">http://wiki.creativecommons.org/CC_REL</a><br><br>If "No" proceed to question 47.',
    )
    license_embedded_url = URLField(
        "Please provide a URL to an example page with embedded licensing information",
        [
            OptionalIf('license_embedded',
                       optvals=Choices.licence_embedded_url_optional()),
            URLOptionalScheme()
        ])
    license = RadioField(
        "Does the journal allow reuse and remixing of content in accordance with a Creative Commons license or <em>other</em> type of license with similar conditions (Select 'Other')?",
        [
            validators.DataRequired(),
            ExtraFieldRequiredIf('license_other',
                                 reqval=Choices.licence_val("other"))
        ],
        choices=Choices._licence,
        description=
        'For more information go to <a href="http://creativecommons.org/licenses/" target="_blank">http://creativecommons.org/licenses/</a>'
    )
    license_other = StringField('License (Other)', )
    license_checkbox = DOAJSelectMultipleField(
        'Which of the following does the content require? (Tick all that apply.)',
        choices=Choices.licence_checkbox(),
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False),
    )
    license_url = URLField(
        "Enter the URL on your site where your license terms are stated",
        [validators.Optional(), URLOptionalScheme()])
    open_access = RadioField(
        "Does the journal allow readers to <em>read, download, copy, distribute, print, search, or link to the full texts of its articles</em> and allow readers to <em>use them for any other lawful purpose</em>?",
        [validators.DataRequired()],
        choices=Choices.open_access(),
        description=
        'From the <a href="http://www.budapestopenaccessinitiative.org/read" target="_blank">Budapest Open Access Initiative\'s definition of Open Access</a>.',
    )
    deposit_policy = DOAJSelectMultipleField(
        'With which deposit policy directory does the journal have a registered deposit policy?',
        [
            validators.DataRequired(),
            ExtraFieldRequiredIf(
                'deposit_policy_other',
                reqval=Choices.deposit_policy_other_val("other")),
            ExclusiveCheckbox()
        ],
        description='Select all that apply.',
        choices=Choices.deposit_policy(),
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False))
    deposit_policy_other = StringField('Deposit Policy (Other)', )
    copyright = RadioField(
        'Does the journal allow the author(s) to hold the copyright without restrictions?',
        [validators.DataRequired()],
        choices=Choices.copyright())
    copyright_url = URLField(
        'Enter the URL where this information can be found', [
            OptionalIf('copyright', optvals=Choices.copyright_url_optional()),
            URLOptionalScheme()
        ])
    publishing_rights = RadioField(
        'Will the journal allow the author(s) to retain publishing rights without restrictions?',
        [validators.DataRequired()],
        choices=Choices.publishing_rights())
    publishing_rights_url = URLField(
        'Enter the URL where this information can be found', [
            OptionalIf('publishing_rights',
                       optvals=Choices.publishing_rights_url_optional()),
            URLOptionalScheme()
        ])
예제 #7
0
class MultiCheckboxField(SelectMultipleField):
    """
    Field for selecting multiple fields from checkbox list.
    """
    widget = widgets.ListWidget(html_tag='ul', prefix_label=False)
    option_widget = widgets.CheckboxInput()
예제 #8
0
class AddGameForm(Form):
    title = TextField('Username', [Required(message='Title Required')])
    description = TextAreaField('Description',
                                [Required(message='Description Required')])
    price = DecimalField('Price', [Required(message='A Price is required')],
                         places=2)

    discount = IntegerField("Discount", [
        NumberRange(min=0, max=100, message="Discount must be between 0-100")
    ])
    discount_expirable = BooleanField("Expirable")
    discount_end_date = DateTimeField("End Date")
    discount_start_date = DateTimeField("Start Date")

    developer = TextField('Developer')
    publisher = TextField('Publisher')
    status = SelectField(u'Field name', choices=["coming soon", "available"])
    features = TextAreaField('Features')
    other_details = TextAreaField('Other Details')
    languages = TextAreaField('Languages')
    image_main = FileField("Main Image")
    image_banner = FileField("Banner Image")

    win_available = BooleanField("Available")
    win_min_os = TextField('Minimum OS')
    win_min_processor = TextField('Minimum Processor')
    win_min_memory = TextField('Minimum Memory')
    win_min_storage = TextField('Minimum Storage')
    win_min_graphics = TextField('Minimum Graphics')
    win_max_os = TextField('Recommended OS')
    win_max_processor = TextField('Recommended Processor')
    win_max_memory = TextField('Recommended Memory')
    win_max_storage = TextField('Recommended Storage')
    win_max_graphics = TextField('Recommended Graphics')

    linux_available = BooleanField("Available")
    linux_min_os = TextField('Minimum OS')
    linux_min_processor = TextField('Minimum Processor')
    linux_min_memory = TextField('Minimum Memory')
    linux_min_storage = TextField('Minimum Storage')
    linux_min_graphics = TextField('Minimum Graphics')
    linux_max_os = TextField('Recommended OS')
    linux_max_processor = TextField('Recommended Processor')
    linux_max_memory = TextField('Recommended Memory')
    linux_max_storage = TextField('Recommended Storage')
    linux_max_graphics = TextField('Recommended Graphics')

    mac_available = BooleanField("Available")
    mac_min_os = TextField('Minimum OS')
    mac_min_processor = TextField('Minimum Processor')
    mac_min_memory = TextField('Minimum Memory')
    mac_min_storage = TextField('Minimum Storage')
    mac_min_graphics = TextField('Minimum Graphics')
    mac_max_os = TextField('Recommended OS')
    mac_max_processor = TextField('Recommended Processor')
    mac_max_memory = TextField('Recommended Memory')
    mac_max_storage = TextField('Recommended Storage')
    mac_max_graphics = TextField('Recommended Graphics')

    tags = QuerySelectMultipleField('Tag',
                                    query_factory=lambda: Tag.query.all(),
                                    widget=widgets.ListWidget(
                                        html_tag="ol", prefix_label=False),
                                    option_widget=widgets.CheckboxInput(),
                                    get_label='title')
예제 #9
0
class MultiCheckboxField(SelectMultipleField):  # поле с выпадающими чекбоксами
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
예제 #10
0
def add_fields(form: Any, class_: str, code: Union[str, None],
               entity: Union[Entity, Node, Link,
                             None], origin: Union[Entity, Node, None]) -> None:
    if class_ == 'actor_actor_relation':
        setattr(form, 'inverse', BooleanField(_('inverse')))
        if not entity:
            setattr(form, 'actor',
                    TableMultiField(_('actor'), [InputRequired()]))
            setattr(form, 'relation_origin_id', HiddenField())
    elif class_ == 'artifact':
        setattr(form, 'actor', TableField(_('owned by')))
    elif class_ in ['activity', 'acquisition', 'move']:
        setattr(form, 'event_id', HiddenField())
        setattr(form, 'event', TableField(_('sub event of')))
        if class_ == 'activity':
            setattr(form, 'place', TableField(_('location')))
        if class_ == 'acquisition':
            setattr(form, 'place', TableField(_('location')))
            setattr(form, 'given_place', TableMultiField(_('given place')))
        elif class_ == 'move':
            setattr(form, 'place_from', TableField(_('from')))
            setattr(form, 'place_to', TableField(_('to')))
            setattr(form, 'artifact', TableMultiField())
            setattr(form, 'person', TableMultiField())
    elif class_ == 'file' and not entity:
        setattr(form, 'file', MultipleFileField(_('file'), [InputRequired()]))
        if origin and origin.class_.view == 'reference':
            setattr(form, 'page', StringField())
    elif class_ == 'group':
        setattr(form, 'residence', TableField(_('residence')))
        setattr(form, 'begins_in', TableField(_('begins in')))
        setattr(form, 'ends_in', TableField(_('ends in')))
    elif class_ == 'hierarchy':
        if code == 'custom' or (entity and not entity.value_type):
            setattr(
                form, 'multiple',
                BooleanField(_('multiple'),
                             description=_('tooltip hierarchy multiple')))
        setattr(
            form, 'forms',
            SelectMultipleField(_('classes'),
                                render_kw={'disabled': True},
                                description=_('tooltip hierarchy forms'),
                                choices=[],
                                option_widget=widgets.CheckboxInput(),
                                widget=widgets.ListWidget(prefix_label=False),
                                coerce=int))
    elif class_ == 'involvement':
        if not entity and origin:
            involved_with = 'actor' \
                if origin.class_.view == 'event' else 'event'
            setattr(form, involved_with,
                    TableMultiField(_(involved_with), [InputRequired()]))
        setattr(form, 'activity', SelectField(_('activity')))
    elif class_ == 'member' and not entity:
        setattr(form, 'member_origin_id', HiddenField())
        setattr(form, 'actor' if code == 'member' else 'group',
                TableMultiField(_('actor'), [InputRequired()]))
    elif class_ in g.classes and g.classes[class_].view == 'type':
        setattr(form, 'is_node_form', HiddenField())
        node = entity if entity else origin
        root = g.nodes[node.root[-1]] if node.root else node
        setattr(form, str(root.id), TreeField(str(root.id)))
        if root.directional:
            setattr(form, 'name_inverse', StringField(_('inverse')))
    elif class_ == 'person':
        setattr(form, 'residence', TableField(_('residence')))
        setattr(form, 'begins_in', TableField(_('born in')))
        setattr(form, 'ends_in', TableField(_('died in')))
    elif class_ == 'reference_system':
        setattr(form, 'website_url',
                StringField(_('website URL'),
                            [OptionalValidator(), URL()]))
        setattr(form, 'resolver_url',
                StringField(_('resolver URL'),
                            [OptionalValidator(), URL()]))
        setattr(form, 'placeholder', StringField(_('example ID')))
        precision_id = str(Node.get_hierarchy('External reference match').id)
        setattr(form, precision_id, TreeField(precision_id))
        choices = ReferenceSystem.get_form_choices(entity)
        if choices:
            setattr(
                form, 'forms',
                SelectMultipleField(
                    _('classes'),
                    render_kw={'disabled': True},
                    choices=choices,
                    option_widget=widgets.CheckboxInput(),
                    widget=widgets.ListWidget(prefix_label=False),
                    coerce=int))
    elif class_ == 'source':
        setattr(
            form, 'artifact',
            TableMultiField(description=_(
                'Link artifacts as the information carrier of the source')))
예제 #11
0
class SForm(Form):
    sc_list = [('cs.AI', 'Artificial Intelligence'),
               ('cs.CC', 'Computational Complexity'),
               ('cs.CG', 'Computational Geometry'),
               ('cs.CE', 'Computational Engineering, Finance, and Science'),
               ('cs.CL', 'Computation and Language'),
               ('cs.CV', 'Computer Vision and Pattern Recognition'),
               ('cs.CY', 'Computers and Society'),
               ('cs.CR', 'Cryptography and Security'), ('cs.DB', 'Databases'),
               ('cs.DS', 'Data Structures and Algorithms'),
               ('cs.DL', 'Digital Libraries'),
               ('cs.DM', 'Discrete Mathematics'),
               ('cs.DC', 'Distributed, Parallel, and Cluster Computing'),
               ('cs.ET', 'Emerging Technologies'),
               ('cs.FL', 'Formal Languages and Automata Theory'),
               ('cs.GT', 'Computer Science and Game Theory'),
               ('cs.GL', 'General Literature'), ('cs.GR', 'Graphics'),
               ('cs.AR', 'Hardware Architecture'),
               ('cs.HC', 'Human-Computer Interaction'),
               ('cs.IR', 'Information Retrieval'),
               ('cs.IT', 'Information Theory'), ('cs.ML', 'Machine Learning'),
               ('cs.LO', 'Logic in Computer Science'),
               ('cs.MS', 'Mathematical Software'),
               ('cs.MA', 'Multiagent Systems'), ('cs.MM', 'Multimedia'),
               ('cs.NI', 'Networking and Internet Architecture'),
               ('cs.NE', 'Neural and Evolutionary Computation'),
               ('cs.NA', 'Numerical Analysis'), ('cs.OS', 'Operating Systems'),
               ('cs.PF', 'Performance'), ('cs.PL', 'Programming Languages'),
               ('cs.RO', 'Robotics'),
               ('cs.SI', 'Social and Information Networks'),
               ('cs.SE', 'Software Engineering'), ('cs.SD', 'Sound'),
               ('cs.SC', 'Symbolic Computation'),
               ('cs.SY', 'Systems and Control'), ('cs.OH', 'Other')]
    keyword = StringField(u'关键词(多个关键词之间使用 半角逗号(,) 分隔,可为空):',
                          render_kw={
                              "type": 'text',
                              "class": "form-control",
                              "placeholder": "keyword"
                          })
    author = StringField(u'作者(多个作者之间使用 半角逗号(,) 分隔,可为空):',
                         render_kw={
                             "type": 'text',
                             "class": "form-control",
                             "placeholder": "author"
                         })
    period = IntegerField(u'监测时间间隔(1-31):',
                          default=7,
                          validators=[
                              InputRequired(message=u'取值范围为1-31天!'),
                              NumberRange(1, 31, message=u'取值为1-31天!')
                          ],
                          render_kw={
                              "type": 'number',
                              "class": "form-control",
                              "placeholder": "period"
                          })
    func = RadioField(label=u"功能(监测需要先登陆):",
                      choices=(
                          (0, "预览查询最多5篇论文"),
                          (1, "监测"),
                      ),
                      coerce=int,
                      default=0)
    subjectCategory = SelectMultipleField(
        u'主题(默认已选择部分与安全相关的主题):',
        choices=sc_list,
        # choices=sorted(sc_list, key=lambda x: len(x[1])),
        default=[
            "cs.AI", "cs.CR", "cs.SE", "cs.CY", "cs.SE", "cs.CE", "cs.ML",
            "cs.CL", "cs.LG", "cs.DS"
        ],
        validators=[InputRequired(message=u'请至少选择一个主题!')],
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False))

    def __init__(self, *args, **kwargs):
        super(SForm, self).__init__(*args, **kwargs)

    @classmethod
    def get_sc_name(cls, sc):
        return [sc_[1] for k in sc for sc_ in cls.sc_list if k == sc_[0]]

    def get_arg(self):
        kw = self.keyword.data.strip()  # 关键词
        au = self.author.data.strip()  # 作者
        sc = self.subjectCategory.data  # 主题
        fc = int(self.func.data)
        sp = int(self.period.data)  # 时期
        if ' ' in kw:
            kw = re.split(r",+", kw)
            kw = list(map(str.strip, kw))
        if ',' in au:
            au = re.split(r",+", au)
            au = list(map(str.strip, au))
        arg_dict = {
            'keyword': kw,
            'author': au,
            'Subject_Category': sc,
            'Subject_Category_name': self.get_sc_name(sc),
            'period': sp,
            'function': fc
        }
        return arg_dict
예제 #12
0
class CompleteForm(FlaskForm):
    habits = SelectMultipleField('Habits', coerce=int,
                                 widget=widgets.TableWidget(),
                                 option_widget=widgets.CheckboxInput())
    submit = SubmitField('Submit Completed Habits')
예제 #13
0
class SelectManyMonkeyForm(Form):
    example = SelectMultipleField(
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False))
예제 #14
0
파일: forms.py 프로젝트: RC-OTOLI/Group12
class MultiCheckboxField(SelectMultipleField):
    """Checkbox for Delete Form"""
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
예제 #15
0
class EditUserForm(FlaskForm):
    roles = SelectMultipleField('Roles',
                                choices=[(str(role.id), role.description)
                                         for role in Role.query.all()],
                                option_widget=widgets.CheckboxInput(),
                                widget=widgets.ListWidget(prefix_label=False))
예제 #16
0
class MultiCheckboxField(SelectMultipleField):
    widget = widgets.TableWidget(with_table_tag=True)
    option_widget = widgets.CheckboxInput()
    coerce = str
예제 #17
0
def generate_submission_edit_form_class(form):
    form_fields = {}
    STATUS_CHOICES = (
        ('', _('Unmarked')),
        ('confirmed', _('Confirmed')),
        ('rejected', _('Rejected')),
        ('citizen', _('Citizen Report')),
    )

    form_fields['contributor'] = CustomModelSelectField(
        _('Participant'),
        allow_blank=True,
        blank_text=_('Participant'),
        widget=widgets.HiddenInput(),
        validators=[validators.optional()],
        model=Participant,
        queryset=participants.find()
        )

    form_fields['location'] = CustomModelSelectField(
        _('Location'),
        allow_blank=True,
        blank_text=_('Location'),
        widget=widgets.HiddenInput(),
        model=Location,
        queryset=locations.find()
        )

    for index, group in enumerate(form.groups):
        for field in group.fields:
            if field.is_comment_field:
                form_fields[field.name] = TextField(
                    field.name,
                    description=field.description,
                    widget=widgets.TextArea())
            elif field.options:
                choices = [(v, k) for k, v in field.options.iteritems()]

                if field.allows_multiple_values:
                    form_fields[field.name] = SelectMultipleField(
                        field.name,
                        choices=choices,
                        coerce=int,
                        description=field.description,
                        filters=[lambda data: data if data else None],
                        validators=[validators.optional()],
                        option_widget=widgets.CheckboxInput(),
                        widget=widgets.ListWidget()
                    )
                else:
                    form_fields[field.name] = IntegerField(
                        field.name,
                        description=field.description,
                        validators=[
                            validators.optional(),
                            validators.AnyOf([v for v, k in choices])],
                        widget=widgets.TextInput()
                    )
            else:
                if form.form_type == 'CHECKLIST':
                    form_fields[field.name] = IntegerField(
                        field.name,
                        description=field.description,
                        validators=[
                            validators.optional(),
                            validators.NumberRange(min=field.min_value,
                                                   max=field.max_value)]
                    )
                else:
                    form_fields[field.name] = BooleanField(
                        field.name,
                        description=field.description,
                        filters=[lambda data: 1 if data else None],
                        validators=[validators.optional()]
                    )

    if (
        form.form_type == 'CHECKLIST' and
        permissions.edit_submission_quarantine_status.can()
    ):
        form_fields['quarantine_status'] = SelectField(
            choices=Submission.QUARANTINE_STATUSES,
            filters=[lambda data: data if data else ''],
            validators=[validators.optional()]
            )

    if (
        form.form_type == 'CHECKLIST' and
        permissions.edit_submission_verification_status.can()
    ):
        form_fields['verification_status'] = SelectField(
            choices=Submission.VERIFICATION_STATUSES,
            filters=[lambda data: data if data else ''],
            validators=[validators.optional()]
            )

    if form.form_type == 'INCIDENT':
        form_fields['status'] = SelectField(
            choices=STATUS_CHOICES,
            filters=[lambda data: data if data else None],
            validators=[validators.optional()]
        )
        form_fields['description'] = StringField(
            widget=widgets.TextArea()
        )
        form_fields['validate'] = validate_location

    return type(
        'SubmissionEditForm',
        (WTSecureForm,),
        form_fields
    )
예제 #18
0
class RegisterForm(Form):
    name = simple.StringField(label='用户名',
                              validators=[validators.DataRequired()],
                              widget=widgets.TextInput(),
                              render_kw={'class': 'form-control'},
                              default='sff')

    pwd = simple.PasswordField(
        label='密码',
        validators=[validators.DataRequired(message='密码不能为空.')],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control'})

    pwd_confirm = simple.PasswordField(
        label='重复密码',
        validators=[
            validators.DataRequired(message='重复密码不能为空.'),
            validators.EqualTo('pwd', message="两次密码输入不一致")
        ],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control'})

    email = html5.EmailField(label='邮箱',
                             validators=[
                                 validators.DataRequired(message='邮箱不能为空.'),
                                 validators.Email(message='邮箱格式错误')
                             ],
                             widget=widgets.TextInput(input_type='email'),
                             render_kw={'class': 'form-control'})

    gender = core.RadioField(
        label='性别',
        choices=(
            (1, '男'),
            (2, '女'),
        ),
        coerce=int  # “1” “2”
    )
    city = core.SelectField(label='城市', choices=(
        ('bj', '北京'),
        ('sh', '上海'),
    ))

    hobby = core.SelectMultipleField(label='爱好',
                                     choices=(
                                         (1, '篮球'),
                                         (2, '足球'),
                                     ),
                                     coerce=int)

    favor = core.SelectMultipleField(
        label='喜好',
        choices=(
            (1, '篮球'),
            (2, '足球'),
        ),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput(),
        coerce=int,
        default=[1, 2])

    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.favor.choices = ((1, '篮球'), (2, '足球'), (3, '羽毛球'))

    def validate_pwd_confirm(self, field):
        """
        自定义pwd_confirm字段规则,例:与pwd字段是否一致
        :param field:
        :return:
        """
        # 最开始初始化时,self.data中已经有所有的值

        if field.data != self.data['pwd']:
            # raise validators.ValidationError("密码不一致") # 继续后续验证
            raise validators.StopValidation("密码不一致")  # 不再继续后续验证
예제 #19
0
class MultipleOccurrenceForm(Form):
    day = DateTimeField(default=datetime.now())
    '''
        label=_('Date'),
        initial=date.today,
        widget=SelectDateWidget()
    )

    start_time_delta = forms.IntegerField(
        label=_('Start time'),
        widget=forms.Select(choices=default_timeslot_offset_options)
    )

    end_time_delta = forms.IntegerField(
        label=_('End time'),
        widget=forms.Select(choices=default_timeslot_offset_options)
    )
    # recurrence options
    repeats = forms.ChoiceField(
        choices=REPEAT_CHOICES,
        initial='count',
        label=_('Occurrences'),
        widget=forms.RadioSelect()
    )
    '''
    # recurrence options

    repeats = RadioField('Occurrences', [validators.Required()],
                         choices=REPEAT_CHOICES,
                         default='count')
    count = IntegerField('Total Occurrences', default=1)

    until = DateTimeField(default=datetime.now())

    freq = RadioField('Frequency',
                      default=rrule.WEEKLY,
                      choices=FREQUENCY_CHOICES)

    interval = IntegerField(default=1)

    # weekly options
    week_days = SelectMultipleField(
        'Weekly options',
        choices=WEEKDAY_SHORT,
        widget=widgets.ListWidget(prefix_label=True),
        option_widget=widgets.CheckboxInput())

    # monthly  options

    month_option = RadioField('Monthly options',
                              default='each',
                              choices=[('on', 'On the'), ('each', 'Each:')])

    #

    #
    month_ordinal_day = SelectField(choices=WEEKDAY_LONG)
    each_month_day = SelectMultipleField(
        choices=[(i, "__" + str(i)) for i in range(1, 32)],
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False))

    # yearly options
    year_months = SelectMultipleField(
        'Yearly options',
        choices=MONTH_SHORT,
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False))

    is_year_month_ordinal = BooleanField()

    year_month_ordinal = SelectField(choices=ORDINAL)
    year_month_ordinal_day = SelectField(choices=WEEKDAY_LONG)

    #---------------------------------------------------------------------------
    def __init__(self, *args, **kws):
        super(MultipleOccurrenceForm, self).__init__(*args, **kws)
        dtstart = datetime.now()
        if dtstart:
            dtstart = dtstart.replace(
                minute=((dtstart.minute // MINUTES_INTERVAL) *
                        MINUTES_INTERVAL),
                second=0,
                microsecond=0)

            weekday = dtstart.isoweekday()
            ordinal = dtstart.day // 7
            ordinal = '%d' % (-1 if ordinal > 3 else ordinal + 1, )
            offset = (dtstart -
                      datetime.combine(dtstart.date(), time(0))).seconds
            '''
            self.initial.setdefault('day', dtstart)
            self.initial.setdefault('week_days', '%d' % weekday)
            self.initial.setdefault('month_ordinal', ordinal)
            self.initial.setdefault('month_ordinal_day', '%d' % weekday)
            self.initial.setdefault('each_month_day', ['%d' % dtstart.day])
            self.initial.setdefault('year_months', ['%d' % dtstart.month])
            self.initial.setdefault('year_month_ordinal', ordinal)
            self.initial.setdefault('year_month_ordinal_day', '%d' % weekday)
            self.initial.setdefault('start_time_delta', '%d' % offset)
            self.initial.setdefault('end_time_delta', '%d' % (offset + SECONDS_INTERVAL,))
            '''

    #---------------------------------------------------------------------------

    def print_all(self):
        if self.day:
            print "day"
            print self.day
            print self.day.data
        else:
            print "None"

        if self.repeats:
            print "repeats"
            print self.repeats.data
        else:
            print "None"

        if self.count:
            print "count"
            print self.count.data
        else:
            print "None"

        if self.until:
            print "until"
            print self.until
            print self.until.data
        else:
            print "None"

        if self.freq:
            print "freq"
            print self.freq.data
        else:
            print "None"

        if self.interval:
            print "interval"
            print self.interval.data
        else:
            print "None"

        if self.week_days:
            print "week_days"
            print self.week_days.data
        else:
            print "None"

        if self.month_option:
            print "month_option"
            print self.month_option.data
        else:
            print "None"

        if self.month_ordinal:
            print "month_ordinal"
            print self.month_ordinal.data
        else:
            print "None"

        if self.month_ordinal_day:
            print "month_ordinal_day"
            print self.month_ordinal_day.data
        else:
            print "None"

        if self.each_month_day:
            print "each_month_day"
            print self.each_month_day.data
        else:
            print "None"

        if self.year_months:
            print "year_months"
            print self.year_months.data
        else:
            print "None"

        if self.is_year_month_ordinal:
            print "is_year_month_ordinal"
            print self.is_year_month_ordinal.data
        else:
            print "None"

        if self.year_month_ordinal:
            print "year_month_ordinal"
            print self.year_month_ordinal.data
        else:
            print "None"

        if self.year_month_ordinal_day:
            print "year_month_ordinal_day"
            print self.year_month_ordinal_day.data
        else:
            print "None"

        params = self.build_rrule_params()
        print params
        return params

    #---------------------------------------------------------------------------
    def clean(self):
        day = datetime.combine(self.cleaned_data['day'], time(0))
        self.cleaned_data['start_time'] = day + timedelta(
            seconds=self.cleaned_data['start_time_delta'])

        self.cleaned_data['end_time'] = day + timedelta(
            seconds=self.cleaned_data['end_time_delta'])

        return self.cleaned_data

    #---------------------------------------------------------------------------
    def save(self, event):
        if self.cleaned_data['repeats'] == 'count' and self.cleaned_data[
                'count'] == 1:
            params = {}
        else:
            params = self._build_rrule_params()

        event.add_occurrences(self.cleaned_data['start_time'],
                              self.cleaned_data['end_time'], **params)

        return event

    #---------------------------------------------------------------------------
    def build_rrule_params(self):
        iso = ISO_WEEKDAYS_MAP
        #     data = self.cleaned_data
        params = dict(freq=int(self.freq.data),
                      interval=int(self.interval.data) or 1)

        if self.repeats.data == 'until':
            params['until'] = self.until.data
        else:
            params['count'] = self.count.data

        if params['freq'] == rrule.WEEKLY:
            v = []
            for x in self.week_days.data:
                y = int(x)
                v.append(y)
            params['byweekday'] = [iso[n] for n in v]

        elif params['freq'] == rrule.MONTHLY:
            if 'on' == self.month_option.data:
                ordinal = self.month_ordinal.data
                day = iso[self.month_ordinal_day.data]
                params.update(byweekday=day, bysetpos=ordinal)
            else:
                params['bymonthday'] = self.each_month_day.data

        elif params['freq'] == rrule.YEARLY:
            params['bymonth'] = self.year_months.data
            if self.is_year_month_ordinal.data:
                ordinal = self.year_month_ordinal.data
                day = iso[self.year_month_ordinal_day.data]
                params['byweekday'] = day(ordinal)

        elif params['freq'] != rrule.DAILY:
            raise NotImplementedError(
                ('Unknown interval rule ' + params['freq']))

        return params
예제 #20
0
class DepartmentMemberForm(FlaskForm):#Form for the member to be added to the department
    name = StringField('Name', [DataRequired()])
    position = SelectField('Position', choices=[('head', 'Head'), ('secretary', 'Secretary'), ('treasurer', 'Treasurer'), ('publicity', 'Publicity'), ('communications', 'Communications')])
    
    departments = SelectMultipleField('Departments', coerce=int,  widget=widgets.ListWidget(prefix_label=True), option_widget=widgets.CheckboxInput())

    def set_choices(self):
        self.departments.choices = [(d.id, d.name) for d in Department.query.all()]
예제 #21
0
class MultiCheckboxField(SelectMultipleField):
    """A wrapper for a SelectMultipleField."""

    widget = widgets.ListWidget
    option_widget = widgets.CheckboxInput()
예제 #22
0
class AnimeFilterForm(Form):
    """Represents an Filter Form for the user's MAL"""
    malIdStart = IntegerField('MAL ID start', validators=[Optional()])
    malIdEnd = IntegerField('MAL ID end', validators=[Optional()])
    type = SelectMultipleField('Type',
                               choices=list(AA_TYPE.items()),
                               widget=widgets.ListWidget(prefix_label=False),
                               option_widget=widgets.CheckboxInput(),
                               coerce=int,
                               validators=[Optional()])
    showStatus = SelectMultipleField(
        'Show Status',
        choices=list(AA_STATUS.items()),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput(),
        coerce=int,
        validators=[Optional()])
    myStatus = SelectMultipleField(
        'My Status',
        choices=list(MAL_STATUS.items()),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput(),
        coerce=int,
        validators=[Optional()],
        default=[1, 2, 3, 4, 6])
    genresInclude = SelectMultipleField(
        'Include genres',
        choices=sorted(list(AA_GENRES.items()), key=lambda x: x[1]),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput(),
        coerce=int,
        validators=[Optional()])
    genresExclude = SelectMultipleField(
        'Exclude genres',
        choices=sorted(list(AA_GENRES.items()), key=lambda x: x[1]),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput(),
        coerce=int,
        validators=[Optional()])
    title = StringField('Title keyword', validators=[Optional()])
    startDateStart = DateField('Aired from start',
                               format='%m/%d/%Y',
                               validators=[Optional()])
    startDateEnd = DateField('Aired from end',
                             format='%m/%d/%Y',
                             validators=[Optional()])
    endDateStart = DateField('Aired to start',
                             format='%m/%d/%Y',
                             validators=[Optional()])
    endDateEnd = DateField('Aired to end',
                           format='%m/%d/%Y',
                           validators=[Optional()])
    scoreStart = DecimalField('MAL score start',
                              validators=[NumberRange(1, 10),
                                          Optional()])
    scoreEnd = DecimalField('Mal score end',
                            validators=[NumberRange(1, 10),
                                        Optional()])
    membersStart = IntegerField('Members count start', validators=[Optional()])
    membersEnd = IntegerField('Members count end', validators=[Optional()])
    episodeGreaterThan = IntegerField('Episode count start',
                                      validators=[Optional()])
    episodeLessThan = IntegerField('Episode count end',
                                   validators=[Optional()])
    episodeWatchedStart = IntegerField('Episode watched start',
                                       validators=[Optional()])
    episodeWatchedEnd = IntegerField('Episode watched end',
                                     validators=[Optional()])
    myWatchDateStart = DateField('Started Watching',
                                 format='%m/%d/%Y',
                                 validators=[Optional()])
    myWatchDateEnd = DateField('Finished Watching',
                               format='%m/%d/%Y',
                               validators=[Optional()])
    myScoreStart = DecimalField('my score start',
                                validators=[NumberRange(1, 10),
                                            Optional()])
    myScoreEnd = DecimalField('my score end',
                              validators=[NumberRange(1, 10),
                                          Optional()])
    rewatchEpisodesStart = IntegerField('episode rewatched start',
                                        validators=[Optional()])
    rewatchEpisodesEnd = IntegerField('episode rewatched end',
                                      validators=[Optional()])
    updateDateStart = DateField('update date start',
                                format='%m/%d/%Y',
                                validators=[Optional()])
    updateDateEnd = DateField('update date end',
                              format='%m/%d/%Y',
                              validators=[Optional()])

    fields = SelectMultipleField(
        'Return fields',
        choices=list(ANIME_USER_ATTRS.items()),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput(),
        default=['title', 'description', 'myScore', 'score', 'imgLink'],
        validators=[DataRequired()])

    submit = SubmitField('Filter Anime')

    def get_data(self):
        """
        Get a list of data contained by the form in printable format

        :return: List of form data
        """
        my_data = self.data
        date_fields = [
            'startDateStart', 'startDateEnd', 'endDateStart', 'endDateEnd',
            'updateDateStart', 'updateDateEnd'
        ]

        for field in date_fields:
            my_data[field] = date_to_string(my_data[field])

        return my_data
예제 #23
0
class MultiCheckboxField(SelectMultipleField):
    widget = widgets.TableWidget()
    option_widget = widgets.CheckboxInput()
예제 #24
0
class AnimeSearchForm(Form):
    """Represents an Search Form for anime the User has not searched before"""
    malIdStart = IntegerField('MAL ID start', validators=[Optional()])
    malIdEnd = IntegerField('MAL ID end', validators=[Optional()])
    type = SelectMultipleField('Type',
                               choices=list(AA_TYPE.items()),
                               widget=widgets.ListWidget(prefix_label=False),
                               option_widget=widgets.CheckboxInput(),
                               coerce=int,
                               validators=[Optional()])
    status = SelectMultipleField('Status',
                                 choices=list(AA_STATUS.items()),
                                 widget=widgets.ListWidget(prefix_label=False),
                                 option_widget=widgets.CheckboxInput(),
                                 coerce=int,
                                 validators=[Optional()])
    genresInclude = SelectMultipleField(
        'Include genres',
        choices=sorted(list(AA_GENRES.items()), key=lambda x: x[1]),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput(),
        coerce=int,
        validators=[Optional()])
    genresExclude = SelectMultipleField(
        'Exclude genres',
        choices=sorted(list(AA_GENRES.items()), key=lambda x: x[1]),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=widgets.CheckboxInput(),
        coerce=int,
        validators=[Optional()])
    title = StringField('Title keyword', validators=[Optional()])
    startDateStart = DateField('Aired from start',
                               format='%m/%d/%Y',
                               validators=[Optional()])
    startDateEnd = DateField('Aired from end',
                             format='%m/%d/%Y',
                             validators=[Optional()])
    endDateStart = DateField('Aired to start',
                             format='%m/%d/%Y',
                             validators=[Optional()])
    endDateEnd = DateField('Aired to end',
                           format='%m/%d/%Y',
                           validators=[Optional()])
    scoreStart = DecimalField('MAL score start',
                              validators=[NumberRange(1, 10),
                                          Optional()])
    scoreEnd = DecimalField('Mal score end',
                            validators=[NumberRange(1, 10),
                                        Optional()])
    membersStart = IntegerField('Members count start', validators=[Optional()])
    membersEnd = IntegerField('Members count end', validators=[Optional()])

    fields = SelectMultipleField('Return fields',
                                 choices=list(ANIME_ATTRS.items()),
                                 widget=widgets.ListWidget(prefix_label=False),
                                 option_widget=widgets.CheckboxInput(),
                                 default=list(ANIME_ATTRS.keys()),
                                 validators=[DataRequired()])

    submit = SubmitField('Search anime')

    def get_data(self):
        """
        Get a list of data contained by the form in printable format

        :return: List of form data
        """
        my_data = self.data
        date_fields = [
            'startDateStart', 'startDateEnd', 'endDateStart', 'endDateEnd'
        ]

        for field in date_fields:
            my_data[field] = date_to_string(my_data[field])

        return my_data
예제 #25
0
def make_submission_edit_form_class(event, form):
    form_fields = {}

    STATUS_CHOICES = (
        ('', _('Unmarked')),
        ('confirmed', _('Confirmed')),
        ('rejected', _('Rejected')),
        ('citizen', _('Citizen Report')),
    )

    form_fields['participant'] = ParticipantQuerySelectField(
        _('Participant'),
        allow_blank=True,
        blank_text=_('Participant'),
        query_factory=lambda: [],
        get_pk=lambda i: i.id)

    form_fields['location'] = LocationQuerySelectField(
        _('Location'),
        allow_blank=True,
        blank_text=_('Location'),
        query_factory=lambda: [],
        get_pk=lambda i: i.id,
        validators=[validators.Optional()])

    if form.data and 'groups' in form.data:
        for index, group in enumerate(form.data['groups']):
            for field in group['fields']:
                field_type = field.get('type')
                if field_type == 'comment':
                    form_fields[field['tag']] = fields.StringField(
                        field['tag'],
                        description=field['description'],
                        validators=[validators.Optional()],
                        widget=widgets.TextArea())
                elif field_type == 'string':
                    form_fields[field['tag']] = fields.StringField(
                        field['tag'],
                        description=field['description'],
                        validators=[
                            validators.Optional(),
                            NumberStringRange(min=field.get('min', 0),
                                              max=field.get('max', 9999))
                        ])
                elif field_type in ('select', 'multiselect'):
                    choices = [(v, '{} — {}'.format(v, k))
                               for k, v in sorted(field['options'].items(),
                                                  key=lambda x: x[1])]

                    if field_type == 'multiselect':
                        form_fields[field['tag']] = fields.SelectMultipleField(
                            field['tag'],
                            choices=choices,
                            coerce=int,
                            description=field['description'],
                            filters=[lambda data: data if data else None],
                            validators=[validators.Optional()],
                            option_widget=widgets.CheckboxInput(),
                            widget=widgets.ListWidget())
                    else:
                        render_choices = [('', '')] + choices
                        form_fields[field['tag']] = fields.SelectField(
                            field['tag'],
                            choices=render_choices,
                            coerce=single_choice_coerce,
                            description=field['description'],
                            filters=[lambda data: data if data else None],
                            validators=[validators.Optional()])
                else:
                    if field_type in ('category', 'integer'):
                        form_fields[field['tag']] = fields.IntegerField(
                            field['tag'],
                            description=field['description'],
                            validators=[
                                validators.Optional(),
                                validators.NumberRange(min=field.get('min', 0),
                                                       max=field.get(
                                                           'max', 9999))
                            ])
                    elif field_type == 'boolean':
                        form_fields[field['tag']] = fields.BooleanField(
                            field['tag'],
                            description=field['description'],
                            filters=[lambda data: 1 if data else None],
                            validators=[validators.Optional()])

    if form.form_type in ['CHECKLIST', 'SURVEY']:
        if permissions.edit_submission_quarantine_status.can():
            form_fields['quarantine_status'] = fields.SelectField(
                choices=models.Submission.QUARANTINE_STATUSES,
                filters=[lambda data: data if data else ''],
                validators=[validators.Optional()])
        if permissions.edit_submission_verification_status.can():
            form_fields['verified_fields'] = fields.SelectMultipleField(
                _('Verified'),
                choices=[(tag, tag) for tag in form.tags],
                option_widget=widgets.CheckboxInput(),
                validators=[validators.Optional()])

    if form.form_type == 'INCIDENT':
        form_fields['status'] = fields.SelectField(
            choices=STATUS_CHOICES,
            filters=[lambda data: data if data else None],
            validators=[validators.optional()])
        form_fields['description'] = fields.StringField(
            widget=widgets.TextArea())
        form_fields['validate'] = validate_location

    form_fields['unreachable'] = fields.BooleanField()

    return type('SubmissionEditForm', (FlaskForm, ), form_fields)
예제 #26
0
class CheckBoxField(SelectMultipleField):
    widget = widgets.TableWidget(with_table_tag=False)
    # widget = widgets.ListWidget()
    option_widget = widgets.CheckboxInput()
예제 #27
0
파일: forms.py 프로젝트: vkurilin/SHEEP
class MultiCheckboxField(SelectMultipleField):
    """
    field for a multi-checkbox.
    """
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
예제 #28
0
class MultiCheckboxField(SelectMultipleField):
    """
    Hack to get checkbox for the selectmultifield wtform
    """
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
예제 #29
0
class MultiCheckboxField(SelectMultipleField):
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()
예제 #30
0
파일: form.py 프로젝트: acdh-oeaw/OpenAtlas
def add_fields(form: Any, class_: str, code: Union[str, None],
               entity: Union[Entity, Link, ReferenceSystem, Type,
                             None], origin: Union[Entity, Type, None]) -> None:
    if class_ == 'actor_actor_relation':
        setattr(form, 'inverse', BooleanField(_('inverse')))
        if not entity:
            setattr(form, 'actor',
                    TableMultiField(_('actor'), [InputRequired()]))
            setattr(form, 'relation_origin_id', HiddenField())
    elif class_ == 'artifact':
        setattr(form, 'actor', TableField(_('owned by')))
    elif class_ in view_class_mapping['event']:
        setattr(form, 'event_id', HiddenField())
        setattr(form, 'event', TableField(_('sub event of')))
        setattr(form, 'event_preceding', TableField(_('preceding event')))
        if class_ in ['activity', 'acquisition', 'production']:
            setattr(form, 'place', TableField(_('location')))
        if class_ == 'acquisition':
            setattr(form, 'given_place', TableMultiField(_('given place')))
        elif class_ == 'move':
            setattr(form, 'place_from', TableField(_('from')))
            setattr(form, 'place_to', TableField(_('to')))
            setattr(form, 'artifact', TableMultiField())
            setattr(form, 'person', TableMultiField())
        elif class_ == 'production':
            setattr(form, 'artifact', TableMultiField())
    elif class_ == 'file' and not entity:
        setattr(form, 'file', MultipleFileField(_('file'), [InputRequired()]))
        if origin and origin.class_.view == 'reference':
            setattr(form, 'page', StringField())
    elif class_ == 'group':
        setattr(form, 'residence', TableField(_('residence')))
        setattr(form, 'begins_in', TableField(_('begins in')))
        setattr(form, 'ends_in', TableField(_('ends in')))
    elif class_ == 'hierarchy':
        if code == 'custom' or (entity and isinstance(entity, Type)
                                and entity.category != 'value'):
            setattr(
                form, 'multiple',
                BooleanField(_('multiple'),
                             description=_('tooltip hierarchy multiple')))
        setattr(
            form, 'classes',
            SelectMultipleField(_('classes'),
                                render_kw={'disabled': True},
                                description=_('tooltip hierarchy forms'),
                                choices=[],
                                option_widget=widgets.CheckboxInput(),
                                widget=widgets.ListWidget(prefix_label=False)))
    elif class_ == 'involvement':
        if not entity and origin:
            involved_with = 'actor' \
                if origin.class_.view == 'event' else 'event'
            setattr(form, involved_with,
                    TableMultiField(_(involved_with), [InputRequired()]))
        setattr(form, 'activity', SelectField(_('activity')))
    elif class_ == 'actor_function' and not entity:
        setattr(form, 'member_origin_id', HiddenField())
        setattr(form, 'actor' if code == 'member' else 'group',
                TableMultiField(_('actor'), [InputRequired()]))
    elif class_ in g.view_class_mapping['type']:
        setattr(form, 'is_type_form', HiddenField())
        type_ = entity if entity else origin
        if isinstance(type_, Type):
            root = g.types[type_.root[0]] if type_.root else type_
            setattr(form, str(root.id), TreeField(str(root.id)))
            if root.directional:
                setattr(form, 'name_inverse', StringField(_('inverse')))
    elif class_ == 'person':
        setattr(form, 'residence', TableField(_('residence')))
        setattr(form, 'begins_in', TableField(_('born in')))
        setattr(form, 'ends_in', TableField(_('died in')))
    elif class_ == 'reference_system':
        setattr(form, 'website_url',
                StringField(_('website URL'),
                            [OptionalValidator(), URL()]))
        setattr(form, 'resolver_url',
                StringField(_('resolver URL'),
                            [OptionalValidator(), URL()]))
        setattr(form, 'placeholder', StringField(_('example ID')))
        precision_id = str(Type.get_hierarchy('External reference match').id)
        setattr(form, precision_id, TreeField(precision_id))
        if choices := ReferenceSystem.get_class_choices(
                entity):  # type: ignore
            setattr(
                form, 'classes',
                SelectMultipleField(
                    _('classes'),
                    render_kw={'disabled': True},
                    choices=choices,
                    option_widget=widgets.CheckboxInput(),
                    widget=widgets.ListWidget(prefix_label=False)))