def test_sets_of_multiple_single_fields(setup):
    """ Test correct re-injection of multiple sets by WTForms
    Sets - No error situation.
    Fields email_x and telephone_x are valid and should be
    present in the form after validation.
    """
    post = deepcopy(setup)
    post.add(u'email_1', '*****@*****.**')
    post.add(u'email_2', '*****@*****.**')
    post.add(u'email_3', '*****@*****.**')
    post.add(u'telephone_1', '14564678')
    post.add(u'telephone_2', '64578952')
    post.add(u'telephone_3', '31794561')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('email','Email', TextField)
    dynamic_form.add_field('telephone','Telephone', TextField)
    dynamic_form.add_validator('email', InputRequired)
    dynamic_form.add_validator('telephone', InputRequired)
    form = dynamic_form.process(SimpleForm,
                                post)

    assert form.validate() == True
    assert form.email_1.data == '*****@*****.**'
    assert form.email_2.data == '*****@*****.**'
    assert form.email_3.data == '*****@*****.**'
    assert form.email_1() == '<input id="email_1" name="email_1" type="text" value="*****@*****.**">'
    assert form.email_2() == '<input id="email_2" name="email_2" type="text" value="*****@*****.**">'
    assert form.email_3() == '<input id="email_3" name="email_3" type="text" value="*****@*****.**">'
    assert form.telephone_1.data == '14564678'
    assert form.telephone_2.data == '64578952'
    assert form.telephone_3.data == '31794561'
    assert form.telephone_1() == '<input id="telephone_1" name="telephone_1" type="text" value="14564678">'
    assert form.telephone_2() == '<input id="telephone_2" name="telephone_2" type="text" value="64578952">'
    assert form.telephone_3() == '<input id="telephone_3" name="telephone_3" type="text" value="31794561">'
def test_validator_equalto_error_multiple(setup):
    """ Test EqualTo validator
    Multiple sets - Error situation.
    Note that only modile_2 and handy_2 are incorrect.
    """
    post = deepcopy(setup)
    post.add(u'mobile_1', '123456')
    post.add(u'handy_1', '123456')
    post.add(u'mobile_2', '456789')
    post.add(u'handy_2', '987654')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('mobile','Mobile', TextField)
    dynamic_form.add_validator('mobile', EqualTo, '%handy%', message='Please fill in the exact same data as %handy%.')
    dynamic_form.add_field('handy','Handy', TextField)
    dynamic_form.add_validator('handy', EqualTo, '%mobile%', message='Please fill in the exact same data as %mobile%.')
    form = dynamic_form.process(SimpleForm,
                                post)
    
    form.validate()
    assert form.validate() == False
    assert form.errors['mobile_2'] == ['Please fill in the exact same data as handy_2.']
    assert form.errors['handy_2'] == ['Please fill in the exact same data as mobile_2.']
    assert form.mobile_1() == '<input id="mobile_1" name="mobile_1" type="text" value="123456">'
    assert form.handy_1() == '<input id="handy_1" name="handy_1" type="text" value="123456">'
    assert form.mobile_2() == '<input id="mobile_2" name="mobile_2" type="text" value="456789">'
    assert form.handy_2() == '<input id="handy_2" name="handy_2" type="text" value="987654">'
def test_add_single_field_without_validation(setup):
    """ Test correct re-injection of single field by WTForms
    No sets - No error situation.
    Fields email has no validator and this is invalid.
    It should be present after validation.
    """
    post = deepcopy(setup)
    post.add(u'email', '')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('email','Email', TextField)
    form = dynamic_form.process(SimpleForm,
                                post)

    assert form.email() == '<input id="email" name="email" type="text" value="">'
    assert form.email.label.text == 'Email'
def test_add_single_field_without_validation(setup):
    """ Test correct re-injection of single field by WTForms
    No sets - No error situation.
    Fields email has no validator and this is invalid.
    It should be present after validation.
    """
    post = deepcopy(setup)
    post.add(u'email', '')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('email', 'Email', TextField)
    form = dynamic_form.process(SimpleForm, post)

    assert form.email(
    ) == '<input id="email" name="email" type="text" value="">'
    assert form.email.label.text == 'Email'
def test_validator_anyof_error_multiple(setup):
    """ Test AnyOf validator
    Sets - Error situation.
    Note, only hobby_3 has a valid hobby.
    """
    post = deepcopy(setup)
    post.add(u'hobby_1', 'sleeping')
    post.add(u'hobby_2', 'eating')
    post.add(u'hobby_3', 'swimming')
    post.add(u'hobby_4', 'gaming')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('hobby', 'Hobby', TextField)
    dynamic_form.add_validator('hobby',
                               AnyOf, ['cylcing', 'swimming', 'hacking'],
                               message='Please enter only allowed hobbies.')
    form = dynamic_form.process(SimpleForm, post)

    form.validate()
    assert form.validate() == False
    assert form.errors['hobby_1'] == ['Please enter only allowed hobbies.']
    assert form.errors['hobby_2'] == ['Please enter only allowed hobbies.']
    assert form.errors['hobby_4'] == ['Please enter only allowed hobbies.']
    assert form.hobby_1(
    ) == '<input id="hobby_1" name="hobby_1" type="text" value="sleeping">'
    assert form.hobby_2(
    ) == '<input id="hobby_2" name="hobby_2" type="text" value="eating">'
    assert form.hobby_3(
    ) == '<input id="hobby_3" name="hobby_3" type="text" value="swimming">'
    assert form.hobby_4(
    ) == '<input id="hobby_4" name="hobby_4" type="text" value="gaming">'
def test_validator_numberrange_error_multiple(setup):
    """ Test NumberRange validator
    Sets - Error situation.
    Note, only age_3 is within range.
    """
    post = deepcopy(setup)
    post.add(u'age_1', '4')
    post.add(u'age_2', '12')
    post.add(u'age_3', '30')
    post.add(u'age_4', '42')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('age', 'Age', IntegerField)
    dynamic_form.add_validator(
        'age',
        NumberRange,
        min=30,
        max=40,
        message='Please enter an age between %(min)s to %(max)s.')
    form = dynamic_form.process(SimpleForm, post)

    form.validate()
    assert form.validate() == False
    assert form.errors['age_1'] == ['Please enter an age between 30 to 40.']
    assert form.errors['age_2'] == ['Please enter an age between 30 to 40.']
    assert form.errors['age_4'] == ['Please enter an age between 30 to 40.']
    assert form.age_1(
    ) == '<input id="age_1" name="age_1" type="text" value="4">'
    assert form.age_2(
    ) == '<input id="age_2" name="age_2" type="text" value="12">'
    assert form.age_3(
    ) == '<input id="age_3" name="age_3" type="text" value="30">'
    assert form.age_4(
    ) == '<input id="age_4" name="age_4" type="text" value="42">'
def test_validator_length_error_multiple(setup):
    """ Test Length validator
    Multiple sets - Error situation.
    Note that only middle_name_1 is correct.
    """
    post = deepcopy(setup)
    post.add(u'middle_name_1', 'foobar')
    post.add(u'middle_name_2', 'foo')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('middle_name', 'Middle Name', TextField)
    dynamic_form.add_validator(
        'middle_name',
        Length,
        min=4,
        max=10,
        message='Please enter length between 4 and 10 characters.')
    form = dynamic_form.process(SimpleForm, post)

    form.validate()
    assert form.validate() == False
    assert form.errors['middle_name_2'] == [
        'Please enter length between 4 and 10 characters.'
    ]
    assert form.middle_name_1(
    ) == '<input id="middle_name_1" name="middle_name_1" type="text" value="foobar">'
    assert form.middle_name_2(
    ) == '<input id="middle_name_2" name="middle_name_2" type="text" value="foo">'
def test_validator_length_error(setup):
    """ Test Length validator
    No set - Error situation.
    Field middle_name is too short.
    """
    post = deepcopy(setup)
    post.add(u'middle_name', 'foo')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('middle_name', 'Middle Name', TextField)
    dynamic_form.add_validator(
        'middle_name',
        Length,
        min=4,
        max=10,
        message='Please enter length between 4 and 10 characters.')
    form = dynamic_form.process(SimpleForm, post)

    form.validate()
    assert form.validate() == False
    assert form.errors['middle_name'] == [
        'Please enter length between 4 and 10 characters.'
    ]
    assert form.middle_name(
    ) == '<input id="middle_name" name="middle_name" type="text" value="foo">'
def test_sets_of_single_fields(setup):
    """ Test correct re-injection of multiple fields by WTForms
    Sets - No error situation.
    Fields email_x are valid and should be present in
    the form after validation.
    """
    post = deepcopy(setup)
    post.add(u'email_1', '*****@*****.**')
    post.add(u'email_2', '*****@*****.**')
    post.add(u'email_3', '*****@*****.**')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('email', 'Email', TextField)
    dynamic_form.add_validator('email', InputRequired)
    form = dynamic_form.process(SimpleForm, post)

    assert form.validate() == True
    assert form.email_1.data == '*****@*****.**'
    assert form.email_2.data == '*****@*****.**'
    assert form.email_3.data == '*****@*****.**'
    assert form.email_1(
    ) == '<input id="email_1" name="email_1" type="text" value="*****@*****.**">'
    assert form.email_2(
    ) == '<input id="email_2" name="email_2" type="text" value="*****@*****.**">'
    assert form.email_3(
    ) == '<input id="email_3" name="email_3" type="text" value="*****@*****.**">'
def test_dependend_automatic_label_suffix(setup):
    """ Test %% replacement with many fields
    Sets - Error situation.
    Fields email_x and telephone_x should not be blank.
    Merely inducing an error to assert for correct field name replacement.
    """
    post = deepcopy(setup)
    post.add(u'email_1', '')
    post.add(u'telephone_1', '')
    post.add(u'pager_1', '')
    post.add(u'email_2', '')
    post.add(u'telephone_2', '')
    post.add(u'pager_2', '')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('email', 'Email', TextField)
    dynamic_form.add_validator(
        'email',
        InputRequired,
        message='Please fill in %telephone% or %pager%.')
    form = dynamic_form.process(SimpleForm, post)

    form.validate()

    assert form.errors['email_1'] == ['Please fill in telephone_1 or pager_1.']
    assert form.errors['email_2'] == ['Please fill in telephone_2 or pager_2.']
    assert form.email_1(
    ) == '<input id="email_1" name="email_1" type="text" value="">'
    assert form.email_2(
    ) == '<input id="email_2" name="email_2" type="text" value="">'
def test_validator_equalto_correct(setup):
    """ Test EqualTo validator
    No set - No error situation.
    Fields Mobile and Handy are equal.
    """
    post = deepcopy(setup)
    post.add(u'mobile', '123456')
    post.add(u'handy', '123456')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('mobile','Mobile', TextField)
    dynamic_form.add_validator('mobile', EqualTo, 'handy', message='Please fill in the exact same data as handy.')
    dynamic_form.add_field('handy','Handy', TextField)
    dynamic_form.add_validator('handy', EqualTo, 'mobile', message='Please fill in the exact same data as mobile.')
    form = dynamic_form.process(SimpleForm,
                                post)

    form.validate()
    assert form.validate() == True
    assert form.mobile() == '<input id="mobile" name="mobile" type="text" value="123456">'
    assert form.handy() == '<input id="handy" name="handy" type="text" value="123456">'
def test_validator_numberrange_error_multiple(setup):
    """ Test NumberRange validator
    Sets - Error situation.
    Note, only age_3 is within range.
    """
    post = deepcopy(setup)
    post.add(u'age_1', '4')
    post.add(u'age_2', '12')
    post.add(u'age_3', '30')
    post.add(u'age_4', '42')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('age','Age', IntegerField)
    dynamic_form.add_validator('age', NumberRange, min=30, max=40, message='Please enter an age between %(min)s to %(max)s.')
    form = dynamic_form.process(SimpleForm,
                                post)
    
    form.validate()
    assert form.validate() == False
    assert form.errors['age_1'] == ['Please enter an age between 30 to 40.']
    assert form.errors['age_2'] == ['Please enter an age between 30 to 40.']
    assert form.errors['age_4'] == ['Please enter an age between 30 to 40.']
    assert form.age_1() == '<input id="age_1" name="age_1" type="text" value="4">'
    assert form.age_2() == '<input id="age_2" name="age_2" type="text" value="12">'
    assert form.age_3() == '<input id="age_3" name="age_3" type="text" value="30">'
    assert form.age_4() == '<input id="age_4" name="age_4" type="text" value="42">'
def test_dependend_automatic_label_suffix(setup):
    """ Test %% replacement with many fields
    Sets - Error situation.
    Fields email_x and telephone_x should not be blank.
    Merely inducing an error to assert for correct field name replacement.
    """
    post = deepcopy(setup)
    post.add(u'email_1', '')
    post.add(u'telephone_1', '')
    post.add(u'pager_1', '')
    post.add(u'email_2', '')
    post.add(u'telephone_2', '')
    post.add(u'pager_2', '')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('email','Email', TextField)
    dynamic_form.add_validator('email', InputRequired, message='Please fill in %telephone% or %pager%.')
    form = dynamic_form.process(SimpleForm,
                                post)
    
    form.validate()

    assert form.errors['email_1'] == ['Please fill in telephone_1 or pager_1.']
    assert form.errors['email_2'] == ['Please fill in telephone_2 or pager_2.']
    assert form.email_1() == '<input id="email_1" name="email_1" type="text" value="">'
    assert form.email_2() == '<input id="email_2" name="email_2" type="text" value="">'
def test_validator_anyof_error_multiple(setup):
    """ Test AnyOf validator
    Sets - Error situation.
    Note, only hobby_3 has a valid hobby.
    """
    post = deepcopy(setup)
    post.add(u'hobby_1', 'sleeping')
    post.add(u'hobby_2', 'eating')
    post.add(u'hobby_3', 'swimming')
    post.add(u'hobby_4', 'gaming')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('hobby','Hobby', TextField)
    dynamic_form.add_validator('hobby', AnyOf, ['cylcing','swimming','hacking'], message='Please enter only allowed hobbies.')
    form = dynamic_form.process(SimpleForm,
                                post)
    
    form.validate()
    assert form.validate() == False
    assert form.errors['hobby_1'] == ['Please enter only allowed hobbies.']
    assert form.errors['hobby_2'] == ['Please enter only allowed hobbies.']
    assert form.errors['hobby_4'] == ['Please enter only allowed hobbies.']
    assert form.hobby_1() == '<input id="hobby_1" name="hobby_1" type="text" value="sleeping">'
    assert form.hobby_2() == '<input id="hobby_2" name="hobby_2" type="text" value="eating">'
    assert form.hobby_3() == '<input id="hobby_3" name="hobby_3" type="text" value="swimming">'
    assert form.hobby_4() == '<input id="hobby_4" name="hobby_4" type="text" value="gaming">'
def test_long_field_name_replacement(setup):

    """ Test %% replacement with many fields
    Sets - Error situation.
    See if fields with many underscores and digits still
    get picked up correctly by the %field_name% formatter.
    Merely inducing an error to assert for correct field name replacement.
    """
    post = deepcopy(setup)
    post.add(u'a_very_long_10_field_name_1', '')
    post.add(u'yet_another_34_long_2_name_10_1', '')
    post.add(u'a_very_long_10_field_name_2', '')
    post.add(u'yet_another_34_long_2_name_10_2', '')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('a_very_long_10_field_name',
                           'A very long field name', TextField)
    dynamic_form.add_validator('a_very_long_10_field_name',
                               InputRequired,
                               message='Please fill in %a_very_long_10_field_name% or %yet_another_34_long_2_name_10%.')
    dynamic_form.add_field('yet_another_34_long_2_name_10',
                           'A very long field name', TextField)
    dynamic_form.add_validator('yet_another_34_long_2_name_10',
                               InputRequired,
                               message='Please fill in %a_very_long_10_field_name% or %yet_another_34_long_2_name_10%.')
    form = dynamic_form.process(SimpleForm,
                                post)
    
    form.validate()

    assert form.validate() == False
    assert form.errors['a_very_long_10_field_name_1'] == ['Please fill in a_very_long_10_field_name_1 or yet_another_34_long_2_name_10_1.']
    assert form.errors['yet_another_34_long_2_name_10_1'] == ['Please fill in a_very_long_10_field_name_1 or yet_another_34_long_2_name_10_1.']
    assert form.errors['a_very_long_10_field_name_2'] == ['Please fill in a_very_long_10_field_name_2 or yet_another_34_long_2_name_10_2.']
    assert form.errors['yet_another_34_long_2_name_10_2'] == ['Please fill in a_very_long_10_field_name_2 or yet_another_34_long_2_name_10_2.']
    assert form.a_very_long_10_field_name_1() == '<input id="a_very_long_10_field_name_1" name="a_very_long_10_field_name_1" type="text" value="">'
    assert form.yet_another_34_long_2_name_10_1() == '<input id="yet_another_34_long_2_name_10_1" name="yet_another_34_long_2_name_10_1" type="text" value="">'
    assert form.a_very_long_10_field_name_2() == '<input id="a_very_long_10_field_name_2" name="a_very_long_10_field_name_2" type="text" value="">'
    assert form.yet_another_34_long_2_name_10_2() == '<input id="yet_another_34_long_2_name_10_2" name="yet_another_34_long_2_name_10_2" type="text" value="">'
def test_add_single_field_with_validation_error(setup):
    """ Test correct re-injection of single field by WTForms
    No sets - Error situation.
    Fields email is invalid thus should trigger an error
    after validation and be present in the form.
    """
    post = deepcopy(setup)
    post.add(u'email', '')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('email', 'Email', TextField)
    dynamic_form.add_validator('email', InputRequired)
    form = dynamic_form.process(SimpleForm, post)

    assert form.validate() == False
    assert form.errors['email'] == ['This field is required.']
def test_add_single_field_with_validation_success(setup):
    """ Test correct re-injection of single field by WTForms
    No sets - No error situation.
    Fields email is valid and should be present in the form
    after validation.
    """
    post = deepcopy(setup)
    post.add(u'email', 'foo')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('email', 'Email', TextField)
    dynamic_form.add_validator('email', InputRequired)
    form = dynamic_form.process(SimpleForm, post)

    assert form.validate() == True
    assert form.email(
    ) == '<input id="email" name="email" type="text" value="foo">'
def test_validator_anyof_success(setup):
    """ Test NumberRange validator
    No set - No error situation.
    Field hobby has a valid selection.
    """
    post = deepcopy(setup)
    post.add(u'hobby', 'swimming')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('hobby', 'Hobby', TextField)
    dynamic_form.add_validator('hobby',
                               AnyOf, ['cylcing', 'swimming', 'hacking'],
                               message='Please enter only allowed hobbies.')
    form = dynamic_form.process(SimpleForm, post)

    form.validate()
    assert form.validate() == True
    assert form.hobby(
    ) == '<input id="hobby" name="hobby" type="text" value="swimming">'
def test_validator_length_correct(setup):
    """ Test Length validator
    No set - No error situation.
    Field middle_name is of correct length.
    """
    post = deepcopy(setup)
    post.add(u'middle_name', 'foobar')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('middle_name','Middle Name', TextField)
    dynamic_form.add_validator('middle_name', Length, min=4, max=10, message='Please enter length between 4 and 10 characters.')
    form = dynamic_form.process(SimpleForm,
                                post)
    
    form.validate()
    assert form.validate() == True
    assert form.middle_name() == '<input id="middle_name" name="middle_name" type="text" value="foobar">'
def test_add_single_field_with_validation_error(setup):
    """ Test correct re-injection of single field by WTForms
    No sets - Error situation.
    Fields email is invalid thus should trigger an error
    after validation and be present in the form.
    """
    post = deepcopy(setup)
    post.add(u'email', '')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('email','Email', TextField)
    dynamic_form.add_validator('email', InputRequired)
    form = dynamic_form.process(SimpleForm,
                                post)
    
    assert form.validate() == False
    assert form.errors['email'] == ['This field is required.']
def test_add_single_field_with_validation_success(setup):
    """ Test correct re-injection of single field by WTForms
    No sets - No error situation.
    Fields email is valid and should be present in the form
    after validation.
    """
    post = deepcopy(setup)
    post.add(u'email', 'foo')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('email','Email', TextField)
    dynamic_form.add_validator('email', InputRequired)
    form = dynamic_form.process(SimpleForm,
                                post)
    
    assert form.validate() == True
    assert form.email() == '<input id="email" name="email" type="text" value="foo">'
def test_validator_anyof_success(setup):
    """ Test NumberRange validator
    No set - No error situation.
    Field hobby has a valid selection.
    """
    post = deepcopy(setup)
    post.add(u'hobby', 'swimming')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('hobby','Hobby', TextField)
    dynamic_form.add_validator('hobby', AnyOf, ['cylcing','swimming','hacking'], message='Please enter only allowed hobbies.')
    form = dynamic_form.process(SimpleForm,
                                post)
    
    form.validate()
    assert form.validate() == True
    assert form.hobby() == '<input id="hobby" name="hobby" type="text" value="swimming">'
def test_validator_numberrange_success(setup):
    """ Test NumberRange validator
    No set - No error situation.
    Field age is within range.
    """
    post = deepcopy(setup)
    post.add(u'age', '32')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('age','Age', IntegerField)
    dynamic_form.add_validator('age', NumberRange, min=30, max=40, message='Please enter an age between %(min)s to %(max)s.')
    form = dynamic_form.process(SimpleForm,
                                post)
    
    form.validate()
    assert form.validate() == True
    assert form.age() == '<input id="age" name="age" type="text" value="32">'
def test_validator_numberrange_success(setup):
    """ Test NumberRange validator
    No set - No error situation.
    Field age is within range.
    """
    post = deepcopy(setup)
    post.add(u'age', '32')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('age', 'Age', IntegerField)
    dynamic_form.add_validator(
        'age',
        NumberRange,
        min=30,
        max=40,
        message='Please enter an age between %(min)s to %(max)s.')
    form = dynamic_form.process(SimpleForm, post)

    form.validate()
    assert form.validate() == True
    assert form.age() == '<input id="age" name="age" type="text" value="32">'
def test_validator_numberrange_error(setup):
    """ Test NumberRange validator
    No set - Error situation.
    Field age is outside the range.
    """
    post = deepcopy(setup)
    post.add(u'age', '20')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('age','Age', IntegerField)
    dynamic_form.add_validator('age', NumberRange, min=30, max=40, message='Please enter an age between %(min)s to %(max)s.')
    form = dynamic_form.process(SimpleForm,
                                post)
    
    form.validate()
    assert form.validate() == False
    assert form.errors['age'] == ['Please enter an age between 30 to 40.']
    assert form.age() == '<input id="age" name="age" type="text" value="20">'
def test_validator_numberrange_error(setup):
    """ Test NumberRange validator
    No set - Error situation.
    Field age is outside the range.
    """
    post = deepcopy(setup)
    post.add(u'age', '20')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('age', 'Age', IntegerField)
    dynamic_form.add_validator(
        'age',
        NumberRange,
        min=30,
        max=40,
        message='Please enter an age between %(min)s to %(max)s.')
    form = dynamic_form.process(SimpleForm, post)

    form.validate()
    assert form.validate() == False
    assert form.errors['age'] == ['Please enter an age between 30 to 40.']
    assert form.age() == '<input id="age" name="age" type="text" value="20">'
def test_validator_length_error_multiple(setup):
    """ Test Length validator
    Multiple sets - Error situation.
    Note that only middle_name_1 is correct.
    """
    post = deepcopy(setup)
    post.add(u'middle_name_1', 'foobar')
    post.add(u'middle_name_2', 'foo')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('middle_name','Middle Name', TextField)
    dynamic_form.add_validator('middle_name', Length, min=4, max=10, message='Please enter length between 4 and 10 characters.')
    form = dynamic_form.process(SimpleForm,
                                post)
   
    form.validate()
    assert form.validate() == False
    assert form.errors['middle_name_2'] == ['Please enter length between 4 and 10 characters.']
    assert form.middle_name_1() == '<input id="middle_name_1" name="middle_name_1" type="text" value="foobar">'
    assert form.middle_name_2() == '<input id="middle_name_2" name="middle_name_2" type="text" value="foo">'
示例#28
0
def add_review():
    """Deprecaated."""
    return redirect(url_for('review.my_reviews'))
    # Code copy pasted from /review code.
    form = ReviewForm()
    # load all papers assigned to current user
    if current_user.curr_conf_id == 1:
        form.paper_select.choices = [
            (paper.id, paper.title)
            for paper in current_user.papers_reviewed if paper.is_reviewable()]
    else:
        form.paper_select.choices = [
            (paper.id, paper.title)
            for paper in
            current_user.papers_reviewed.filter_by(
                conference_id=current_user.curr_conf_id) if
            paper.is_reviewable()]
    custom_questions = OrderedDict()
    for k, v in current_user.curr_conf.review_questions.items():
        if v['include'] is True and v.get('deleted', False) is False:
            custom_questions[k] = v
    dynamic = WTFormsDynamicFields()
    for id, question in custom_questions.items():
        if question['ques_type'] != 1:
            dynamic.add_field(id, question['desc'], StringField)
        else:
            # handle multi select
            dynamic.add_field(id, question[
                'desc'], SelectMultipleField, choices=[(option, option) for option in question['options']], coerce=str)
        if question['require']:
            dynamic.add_validator(
                id, required, message='This field is required')
    if request.method == 'POST':
        form = dynamic.process(ReviewForm, request.form)
        if current_user.curr_conf_id == 1:
            form.paper_select.choices = [(paper.id, paper.title)
                                         for paper in current_user.papers_reviewed]
        else:
            form.paper_select.choices = [(paper.id, paper.title)
                                         for paper in current_user.papers_reviewed.filter_by(
                conference_id=current_user.curr_conf_id)]
        form.process(request.form)
        if form.validate_on_submit():
            paper = Paper.query.filter_by(id=form.paper_select.data).first()
            # get custom question answer
            custom_question_answer = OrderedDict()
            for id, question in custom_questions.items():
                custom_question_answer[id] = {
                    'answer': form.__dict__.get(id + '_1').data if form.__dict__.get(id + '_1') else "",
                    'ques_type': question['ques_type'],
                    'desc': question['desc']
                }
            # reviewer cannot review same paper more than once
            review = paper.reviews.filter_by(
                reviewer_id=current_user.id).first()
            if review is None:
                review = Review(paper_id=form.paper_select.data,
                                conference_id=paper.conference.id,
                                reviewer=current_user._get_current_object(),
                                evaluation=form.evaluation.data,
                                confidence=form.confidence.data,
                                review_body=form.review_body.data,
                                confidential_comments=form.confidential_remarks.data,
                                custom_question_answer=custom_question_answer)
                db.session.add(review)
                db.session.commit()
                add_event(current_user.first_name + ' ' + current_user.last_name +
                          ' submits a new review on paper ' + paper.title, review.to_json_log())
                # check review delegation
                delegation = DelegateReview.query.filter_by(paper_id=review.paper_id,
                                                            delegatee_id=current_user.id,
                                                            status='Accepted').first()
                if delegation:
                    delegation.review_id = review.id
                    delegation.status = 'Submitted'
                    db.session.add(delegation)
                    db.session.commit()
                flash("Review Submitted", 'success')
            else:
                # update review
                review.evaluation = form.evaluation.data
                review.confidence = form.confidence.data
                review.review_body = form.review_body.data
                review.confidential_comments = form.confidential_remarks.data
                review.custom_question_answer = custom_question_answer
                db.session.add(review)
                db.session.commit()
                add_event(current_user.first_name + ' ' + current_user.last_name +
                          ' updates the review on paper ' + paper.title, review.to_json_log())
                flash('Your review has been updated', 'warning')
        else:
            # print form.errors
            flash(form.errors, 'error')
    return render_template('review/review_add.html',
                           form=form,
                           pdf_url=current_app.config['PDF_URL'],
                           review_process=current_user.curr_conf.configuration.get('review_process'))
示例#29
0
def edit_review(paper_id):
    """Add review for a paper."""
    # Code copy pasted from /review code.
    success_flag = False
    paper = Paper.query.get_or_404(paper_id)
    delegation_flag = paper.if_has_subreview(current_user)
    if not (paper.reviewers.filter_by(
            id=current_user.id).first() or delegation_flag):
        abort(403)
    # current_user can review the paper
    if current_user.curr_conf_id != paper.conference_id:
        current_user.set_conference_id(paper.conference_id)
    form = ReviewForm()
    custom_questions = OrderedDict()
    for k, v in current_user.curr_conf.review_questions.items():
        if v['include'] is True and v.get('deleted', False) is False:
            custom_questions[k] = v
    dynamic = WTFormsDynamicFields()
    for id, question in custom_questions.items():
        if question['ques_type'] != 1:
            dynamic.add_field(id, question['desc'], StringField)
        else:
            # handle multi select
            dynamic.add_field(
                id, question['desc'], SelectMultipleField,
                choices=[(option, option) for option in question['options']],
                coerce=unicode)
        if question['require']:
            dynamic.add_validator(
                id, required, message='This field is required')
    # form.process(request.form)
    if delegation_flag:
        review = Review.query.filter(
            Review.paper_id == paper_id,
            DelegateReview.delegator_id == current_user.id,
            DelegateReview.review_id == Review.id).first()
    else:
        review = paper.reviews.filter_by(reviewer_id=current_user.id).first()
    if review:
        form.evaluation.data = review.evaluation
        form.confidence.data = review.confidence
        form.review_body.data = review.review_body
        form.confidential_remarks.data = review.confidential_comments
    if request.method == 'POST':
        form = dynamic.process(ReviewForm, request.form)
        if form.validate_on_submit():
            custom_question_answer = OrderedDict()
            for id, question in custom_questions.items():
                custom_question_answer[id] = {
                    'answer': form.__dict__.get(id + '_1').data if
                    form.__dict__.get(id + '_1') else '',
                    'ques_type': question['ques_type'],
                    'desc': question['desc']
                }
            # reviewer cannot review same paper more than once
            paper = Paper.query.filter_by(id=paper_id).first()
            if not review:
                review_flag = 'submitted'
                review = Review(
                    paper_id=paper_id,
                    conference_id=paper.conference.id,
                    reviewer_id=current_user.id,
                    evaluation=form.evaluation.data,
                    confidence=form.confidence.data,
                    review_body=form.review_body.data,
                    confidential_comments=form.confidential_remarks.data,
                    custom_question_answer=custom_question_answer)
                db.session.add(review)
                # check review delegation
                delegation = DelegateReview.query.filter_by(
                    paper_id=review.paper_id, delegatee_id=current_user.id,
                    status='Accepted').first()
                if delegation:
                    delegation.review_id = review.id
                    delegation.status = 'Submitted'
                    db.session.add(delegation)
                try:
                    db.session.commit()
                except Exception as e:
                    db.session.rollback()
                    flash(e.message, 'error')
                    return redirect(url_for('review.edit_review',
                                            paper_id=paper_id))
                if delegation:
                    # send notification to delegator
                    send_email(
                        delegation.delegator.email,
                        current_user.full_name + ' submitted a new review',
                        'email/review_delegate_new_review',
                        reply_to=current_user.email,
                        paper=paper,
                        delegation_id=delegation.id)
            else:
                # update review
                review_flag = 'updated'
                review.evaluation = form.evaluation.data
                review.confidence = form.confidence.data
                review.review_body = form.review_body.data
                review.confidential_comments = form.confidential_remarks.data
                review.custom_question_answer = custom_question_answer
                db.session.add(review)
                db.session.commit()
            success_flag = True
            send_email(current_user.email,
                       'A review has been ' + review_flag,
                       'email/review_update',
                       paper=paper)
            add_event(current_user.full_name + '(' + str(current_user.id) +
                      ') ' + review_flag + ' the review on paper: (' +
                      str(paper.id) + ') ' + paper.title,
                      review.to_json_log(),
                      conference_id=paper.conference_id,
                      paper_id=paper.id,
                      review_id=review.id,
                      type='review_new' if review_flag == 'submitted' else
                      'review_update')
        else:
            flash('Problem Validating Form', 'error')
    # comments = ReviewComment.query.filter_by(review_id=review.id).order_by(
    #     ReviewComment.timestamp).all() if review else []
    return render_template('review/review_add.html',
                           form=form,
                           pdf_url=current_app.config['PDF_URL'],
                           configuration=paper.track.configuration if
                           paper.track.configuration.get(
                            'allow_review_config')
                           else paper.conference.configuration,
                           paper=paper, review=review,
                           delegation_flag=delegation_flag,
                           success_flag=success_flag,
                           # comments=comments,
                           current_time=datetime.utcnow(),
                           review_answer=review.custom_question_answer if
                           review else {})
示例#30
0
def add_submission():
    """Add submission to current conf."""
    if request.args.get('conf_id', False):
        conference = Conference.query.get_or_404(request.args['conf_id'])
        if not current_user.is_joined_conference(conference):
            if current_user.can_join_conference(conference,
                                                check_joined=False):
                current_user.join_conference(conference)
            else:
                flash('Conference has ended, You cannot submit paper anymore',
                      'error')
                abort(403)
        current_user.set_conference_id(conference.id)
    conference = current_user.curr_conf
    if conference.id == 1:
        flash('You are not allowed to submit paper to \'Main\'', 'error')
        abort(403)
    # add submission type
    if conference.configuration.get('submission_types', False):
        setattr(PaperForm,
                'submission_type',
                SelectField('Submission type *',
                            coerce=str,
                            choices=[
                                (type, type) for type in
                                conference.configuration.get(
                                    'submission_types', ['']).split(',')]))
    else:
        # remove the submission_type
        if hasattr(PaperForm, 'submission_type'):
            delattr(PaperForm, 'submission_type')
    form = PaperForm()
    tracks = conference.tracks.filter_by(status=True).all()
    if len(tracks) == 1:
        form.track_id.choices = [(tracks[0].id, tracks[0].name)]
        hide_tracks = True
    else:
        form.track_id.choices = [
            (track.id, track.name) for track in tracks if not track.default]
        hide_tracks = False
    dynamic = WTFormsDynamicFields()
    dynamic.add_field('author_sendnotification', '', BooleanField)
    dynamic.add_field('author_email', 'Email *', StringField)
    dynamic.add_field('author_firstname', 'First Name *', StringField)
    dynamic.add_field('author_lastname', 'Last Name *', StringField)
    dynamic.add_field('author_organization', 'Organization *', StringField)
    dynamic.add_field('author_country', 'Country *', StringField)
    dynamic.add_field('author_website', 'Website', StringField)
    dynamic.add_validator('author_email', required,
                          message='This field is required')
    dynamic.add_validator('author_email', email,
                          message='This field is required')
    dynamic.add_validator('author_firstname', required,
                          message='This field is required')
    dynamic.add_validator('author_lastname', required,
                          message='This field is required')
    dynamic.add_validator('author_organization', required,
                          message='This field is required')
    dynamic.add_validator('author_country', required,
                          message='This field is required')
    if conference.submission_questions:
        for id, question in conference.submission_questions.items():
            if question['include'] is True and \
                    question.get('deleted', False) is False:
                if question['ques_type'] != 1:
                    dynamic.add_field(id, question['desc'], StringField)
                else:
                    # handle multi select
                    dynamic.add_field(id, question['desc'],
                                      SelectMultipleField,
                                      choices=[
                                      (option, option) for option in
                                      question['options']],
                                      coerce=str)
                if question['require']:
                    dynamic.add_validator(
                        id, required, message='This field is required')
    # if the submission is not open
    if not conference.configuration.get('submission_process'):
        return render_template('submission/submission_add.html',
                               form=form, user=current_user,
                               submission_closed=True,
                               endpoint='self_submission',
                               pdf_url=current_app.config['PDF_URL'],
                               hide_tracks=hide_tracks)

    if request.method == 'POST':
        form = dynamic.process(PaperForm, request.form)
        # get default track or non default default tracks
        if len(tracks) == 1:
            form.track_id.choices = [(tracks[0].id, tracks[0].name)]
        else:
            form.track_id.choices = [
                (track.id, track.name) for track in tracks
                if not track.default]
        if form.validate_on_submit():
            # print form.filename.data
            paper_file = UserDoc.query.filter(
                and_(UserDoc.id.in_(form.filename.data.split(',')[:-1]),
                     UserDoc.uploader_id == current_user.id)).all()
            if not paper_file:
                flash('Please add a file', 'error')
                return redirect(url_for('submission.add_submission'))
            else:
                custom_question_answer = OrderedDict()
                for id, question in conference.submission_questions.items():
                    custom_question_answer[id] = {
                        'answer':
                        form.__dict__.get(id + '_1').data if form.__dict__.get(
                            id + '_1') else '',
                        'ques_type': question['ques_type'],
                        'desc': question['desc']
                    }

                paper = Paper(filename=paper_file[0].filename,
                              uploader_id=current_user.id,
                              title=form.title.data,
                              abstract=form.abstract.data,
                              keywords=form.keywords.data,
                              comment=form.comment.data,
                              conference_id=conference.id,
                              track_id=form.track_id.data,
                              custom_question_answer=custom_question_answer)
                for doc in paper_file:
                    paper.files.append(doc)
                if conference.configuration.get('submission_types', False):
                    paper.submission_type = form.submission_type.data
                # Turn the dynamic form's data into a dict so we can iterate
                # over it easie
                form_dict = form.__dict__
                i = 1
                authors = []
                while form_dict.get('author_email_' + str(i)):
                    cur_email = form_dict.get('author_email_' + str(i)).data
                    send_email_flag = False
                    user = User.query.filter_by(email=cur_email).first()
                    if user and user.primary_id:
                        # add to primary account
                        user = user.primary_user
                    if user:
                        # check if user has reach maximum submissions
                        if conference.configuration.get(
                                'submission_limit'):
                            if not user.can_submit_paper(conference.id):
                                # delete paper object
                                db.session.delete(paper)
                                flash(user.full_name + ' has reached maximum \
                                      number of submissions', 'error')
                                return redirect(
                                    url_for('submission.add_submission'))
                        # user already existed
                        paper.authors.append(user)
                        authors.append(user.full_name)
                    else:
                        # add new user if the author doesn't exsit in database
                        pwd = User.generate_pwd()
                        user = User(email=cur_email,
                                    password=pwd,
                                    first_name=form_dict.get(
                                        'author_firstname_' + str(i)).data,
                                    last_name=form_dict.get(
                                        'author_lastname_' + str(i)).data,
                                    country=form_dict.get(
                                        'author_country_' + str(i)).data,
                                    website=form_dict.get(
                                        'author_website_' + str(i)).data,
                                    organization=form_dict.get(
                                        'author_organization_' + str(i)).data,
                                    confirmed=True
                                    )
                        try:
                            db.session.add(user)
                            db.session.commit()
                        except Exception as e:
                            db.session.rollback()
                            flash(e.message, 'error')
                            return redirect(
                                url_for('submission.add_submission'))
                        paper.authors.append(user)
                        send_email_flag = True
                        authors.append(user.full_name)
                    author = Author(email=cur_email,
                                    user_id=user.id,
                                    first_name=form_dict.get(
                                        'author_firstname_' + str(i)).data,
                                    last_name=form_dict.get(
                                        'author_lastname_' + str(i)).data,
                                    country=form_dict.get(
                                        'author_country_' + str(i)).data,
                                    website=form_dict.get(
                                        'author_website_' + str(i)).data,
                                    organization=form_dict.get(
                                        'author_organization_' + str(i)).data)
                    paper.authors_list.append(author)
                    db.session.add(author)
                    if send_email_flag:
                        # new user
                        # join conference
                        user.join_conference(conference)
                        # send an email to inform the new user
                        if form_dict.get('author_sendnotification_' + str(i)):
                            send_email(cur_email,
                                       'A paper with you as an author has been \
                                       submitted',
                                       'email/new_account_coauthor',
                                       reply_to=current_user.email,
                                       user=user,
                                       title=form.title.data, password=pwd,
                                       conference=conference.name,
                                       paper_id=paper.id)
                            send_email_flag = False
                    else:
                        # check if joined conference
                        if not user.is_joined_conference(conference):
                            user.join_conference(conference)
                        # send email to inform author
                        if form_dict.get('author_sendnotification_' + str(i)):
                            send_email(cur_email,
                                       'A paper with you as an author has been \
                                       submitted',
                                       'email/submit_notification',
                                       reply_to=current_user.email,
                                       user=user,
                                       title=form.title.data,
                                       conference=conference.name,
                                       paper_id=paper.id)
                    i += 1
                authors = ', '.join(authors)
                if conference.configuration.get(
                        'submissions_notification'):
                    # send email to inform the chair and track chairs.
                    cur_track = Track.query.get_or_404(form.track_id.data)
                    all_chairs = conference.chairs + \
                        cur_track.track_chairs
                    for chair in all_chairs:
                        send_email(chair.email,
                                   '[' +
                                   conference.short_name.upper() +
                                   '] ' + 'A paper has been received',
                                   'email/submit_notification_chair',
                                   reply_to=current_user.email,
                                   chair=chair, authors=authors,
                                   title=form.title.data,
                                   conference=conference.name)
                try:
                    db.session.add(paper)
                    db.session.commit()
                except Exception as e:
                    db.session.rollback()
                    flash(e.message, 'error')
                    return redirect(
                        url_for('submission.add_submission'))
                add_event(current_user.full_name +
                          '(' + str(current_user.id) + ')' +
                          ' submitted paper: (' + str(paper.id) + ') ' +
                          paper.title,
                          paper.to_json_log(),
                          conference_id=paper.conference_id,
                          paper_id=paper.id,
                          type='paper_new')

                flash('Upload Successful', 'success')
                return redirect(
                    url_for('paper.get_paper_info', paper_id=paper.id))
        else:
            flash(form.errors, 'error')
            return redirect(url_for('submission.add_submission'))
    return render_template('submission/submission_add.html',
                           form=form, user=current_user,
                           pdf_url=current_app.config['PDF_URL'],
                           submission_closed=False,
                           endpoint='self_submission',
                           hide_tracks=hide_tracks)
def test_validator_equalto_correct(setup):
    """ Test EqualTo validator
    No set - No error situation.
    Fields Mobile and Handy are equal.
    """
    post = deepcopy(setup)
    post.add(u'mobile', '123456')
    post.add(u'handy', '123456')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('mobile', 'Mobile', TextField)
    dynamic_form.add_validator(
        'mobile',
        EqualTo,
        'handy',
        message='Please fill in the exact same data as handy.')
    dynamic_form.add_field('handy', 'Handy', TextField)
    dynamic_form.add_validator(
        'handy',
        EqualTo,
        'mobile',
        message='Please fill in the exact same data as mobile.')
    form = dynamic_form.process(SimpleForm, post)

    form.validate()
    assert form.validate() == True
    assert form.mobile(
    ) == '<input id="mobile" name="mobile" type="text" value="123456">'
    assert form.handy(
    ) == '<input id="handy" name="handy" type="text" value="123456">'
def test_validator_equalto_error_multiple(setup):
    """ Test EqualTo validator
    Multiple sets - Error situation.
    Note that only modile_2 and handy_2 are incorrect.
    """
    post = deepcopy(setup)
    post.add(u'mobile_1', '123456')
    post.add(u'handy_1', '123456')
    post.add(u'mobile_2', '456789')
    post.add(u'handy_2', '987654')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('mobile', 'Mobile', TextField)
    dynamic_form.add_validator(
        'mobile',
        EqualTo,
        '%handy%',
        message='Please fill in the exact same data as %handy%.')
    dynamic_form.add_field('handy', 'Handy', TextField)
    dynamic_form.add_validator(
        'handy',
        EqualTo,
        '%mobile%',
        message='Please fill in the exact same data as %mobile%.')
    form = dynamic_form.process(SimpleForm, post)

    form.validate()
    assert form.validate() == False
    assert form.errors['mobile_2'] == [
        'Please fill in the exact same data as handy_2.'
    ]
    assert form.errors['handy_2'] == [
        'Please fill in the exact same data as mobile_2.'
    ]
    assert form.mobile_1(
    ) == '<input id="mobile_1" name="mobile_1" type="text" value="123456">'
    assert form.handy_1(
    ) == '<input id="handy_1" name="handy_1" type="text" value="123456">'
    assert form.mobile_2(
    ) == '<input id="mobile_2" name="mobile_2" type="text" value="456789">'
    assert form.handy_2(
    ) == '<input id="handy_2" name="handy_2" type="text" value="987654">'
示例#33
0
def edit_paper_info(paper_id):
    """Edit paper info."""
    paper = Paper.query.get_or_404(paper_id)
    # only author or uploader can edit paper
    conference = paper.conference
    allow_edit_author = False
    if current_user.curr_conf_id != conference.id:
        current_user.set_conference_id(conference.id)
    if not (current_user.id == paper.uploader_id or
            current_user in paper.authors or
            current_user.is_chair(conference)):
        flash('Only authors and uploader can edit this paper', 'error')
        abort(403)
    else:
        allow_edit_author = current_user.is_chair(
            conference) or conference.configuration.get(
                'allow_edit_paper_author')
        if conference.configuration.get('submission_types', False):
            setattr(PaperForm,
                    'submission_type',
                    SelectField('Submission type *',
                                coerce=str,
                                choices=[
                                    (type, type) for type in
                                    conference.configuration.get(
                                        'submission_types').split(',')],
                                default=paper.submission_type))
        else:
            # remove the submission_type
            if hasattr(PaperForm, 'submission_type'):
                delattr(PaperForm, 'submission_type')
        form = PaperForm()
        tracks = conference.tracks.filter_by(status=True).all()
        if len(tracks) == 1:
            form.track_id.choices = [
                (track.id, track.name) for track in tracks]
        else:
            form.track_id.choices = [
                (track.id, track.name) for track in tracks
                if not track.default]
        # withdraw_form = WithdrawForm()
        dynamic = WTFormsDynamicFields()
        dynamic.add_field('author_sendnotification', '', BooleanField)
        dynamic.add_field('author_email', 'Email *', StringField)
        dynamic.add_field('author_firstname', 'First Name *', StringField)
        dynamic.add_field('author_lastname', 'Last Name *', StringField)
        dynamic.add_field('author_organization', 'Organization *', StringField)
        dynamic.add_field('author_country', 'Country *', StringField)
        dynamic.add_field('author_website', 'Website', StringField)
        dynamic.add_validator('author_email', required,
                              message='This field is required')
        dynamic.add_validator('author_email', email,
                              message='This field is required')
        dynamic.add_validator('author_firstname', required,
                              message='This field is required')
        dynamic.add_validator('author_lastname', required,
                              message='This field is required')
        dynamic.add_validator('author_organization',
                              required, message='This field is required')
        dynamic.add_validator('author_country', required,
                              message='This field is required')
        for id, question in conference.submission_questions.items():
            if question['include'] is True and \
                    question.get('deleted', False) is False:
                if question['ques_type'] != 1:
                    dynamic.add_field(id, question['desc'], StringField)
                else:
                    # handle multi select
                    dynamic.add_field(
                        id,
                        question['desc'],
                        SelectMultipleField,
                        choices=[
                            (option, option) for option
                            in question['options']],
                        coerce=str)
                if question['require']:
                    dynamic.add_validator(
                        id, required, message='This field is required')
        if not paper.is_editable(current_user):
            return render_template('paper/paper_info_edit.html', form=form,
                                   user=current_user, paper=paper,
                                   pdf_url=current_app.config['PDF_URL'],
                                   submission_closed=True,
                                   allow_edit_author=allow_edit_author)
        if request.method == 'POST':
            form = dynamic.process(PaperForm, request.form)
            if len(tracks) == 1:
                form.track_id.choices = [
                    (track.id, track.name) for track in tracks]
            else:
                form.track_id.choices = [
                    (track.id, track.name) for track in tracks if
                    not track.default]
            if form.validate_on_submit():
                custom_question_answer = OrderedDict()
                for id, question in conference.submission_questions.\
                        items():
                    custom_question_answer[id] = {
                        'answer':
                            form.__dict__.get(id + '_1').data if
                            form.__dict__.get(id + '_1') else '',
                        'ques_type': question['ques_type'],
                        'desc': question['desc']
                    }
                # filename field now contains ALL papers
                if form.filename.data == '':
                    flash('There is no file for the paper!', 'error')
                    return redirect(
                        url_for('paper.edit_paper_info', paper_id=paper.id))

                new_docs = form.filename.data.split(',')[:-1]

                # files that can be seen by author and chairs
                files_on_record = paper.files.filter_by(
                    status=UserDocStatus.RECEIVED).all()
                for old_file in files_on_record:
                    if str(old_file.id) not in new_docs:
                        # if doc.uploader_id != current_user.id:
                        #     flash('You cannot delete file not uploaded by you',
                        #           'error')
                        #     return render_template(
                        #         'paper/paper_info_edit.html',
                        #         form=form, user=current_user,
                        #         paper=paper,
                        #         pdf_url=current_app.config['PDF_URL'],
                        #         submission_closed=False,
                        #         withdraw_form=withdraw_form)
                        # else:
                        old_file.status = UserDocStatus.DELETED
                        db.session.add(old_file)
                        # db.session.commit()

                paper_files = UserDoc.query.filter(
                    UserDoc.id.in_(new_docs)).all()

                for f in paper_files:
                    paper.files.append(f)

                # update the paper's title, abstract, keywords and comment
                paper.title = form.title.data
                paper.abstract = form.abstract.data
                paper.keywords = form.keywords.data
                paper.comment = form.comment.data
                if conference.configuration.get('submission_types',  False):
                    paper.submission_type = form.submission_type.data
                paper.custom_question_answer = custom_question_answer
                # Turn the dynamic form's data into a dict so we can iterate
                # over it easie
                form_dict = form.__dict__

                if allow_edit_author:
                    i = 1
                    while form_dict.get('author_email_' + str(i)):
                        first_name = form_dict.get(
                            'author_firstname_' + str(i)).data
                        last_name = form_dict.get(
                            'author_lastname_' + str(i)).data
                        if not check_name(first_name, last_name):
                            flash('Some fields have problems. Please check.',
                                  'error')
                            return render_template(
                                'paper/paper_info_edit.html',
                                form=form, user=current_user,
                                paper=paper,
                                pdf_url=current_app.config['PDF_URL'],
                                submission_closed=False,
                                allow_edit_author=allow_edit_author)
                        i += 1

                    # update the paper's author list
                    # empty the list first
                    paper.authors = []
                    paper.authors_list = []
                    i = 1
                    while form_dict.get('author_email_' + str(i)):
                        cur_email = form_dict.get(
                            'author_email_' + str(i)).data
                        user = User.query.filter_by(email=cur_email).first()
                        if user is not None:
                            if user.primary_id:
                                # add to primary account
                                user = user.primary_user
                            if conference.configuration.get(
                                    'submission_limit'):
                                if not user.can_submit_paper(conference.id):
                                    flash(user.full_name +
                                          ' has reached mixmum number of \
                                          submissions', 'error')
                                    return redirect(
                                        url_for('paper.edit_paper_info',
                                                paper_id=paper.id))
                            paper.authors.append(user)
                        else:
                            # add new user if the author doesn't exsit in
                            # database
                            pwd = User.generate_pwd()
                            first_name = form_dict.get(
                                "author_firstname_" + str(i)).data
                            last_name = form_dict.get(
                                "author_lastname_" + str(i)).data
                            user = User(email=cur_email,
                                        password=pwd,
                                        first_name=first_name,
                                        last_name=last_name,
                                        country=form_dict.get(
                                            'author_country_' + str(i)).data,
                                        website=form_dict.get(
                                            'author_website_' + str(i)).data,
                                        organization=form_dict.get(
                                            'author_organization_' + str(i)
                                            ).data,
                                        confirmed=True
                                        )
                            db.session.add(user)
                            db.session.commit()
                            paper.authors.append(user)
                            if form_dict.get(
                                    'author_sendnotification_' + str(i)):
                                send_email(cur_email,
                                           'A paper with you as an author has \
                                           been updated',
                                           'email/new_account_coauthor_update',
                                           reply_to=paper.uploader.email,
                                           user=user,
                                           title=form.title.data,
                                           password=pwd)
                        author = Author(email=cur_email,
                                        user_id=user.id,
                                        first_name=form_dict.get(
                                            'author_firstname_' + str(i)).data,
                                        last_name=form_dict.get(
                                            'author_lastname_' + str(i)).data,
                                        country=form_dict.get(
                                            'author_country_' + str(i)).data,
                                        website=form_dict.get(
                                            'author_website_' + str(i)).data,
                                        organization=form_dict.get(
                                            'author_organization_' + str(i)
                                            ).data)
                        paper.authors_list.append(author)
                        db.session.add(author)
                        # db.session.commit()
                        # send email to inform author
                        if form_dict.get("author_sendnotification_" + str(i)):
                            send_email(cur_email,
                                       'A paper with you as an author has been \
                                       updated',
                                       'email/update_notification',
                                       reply_to=paper.uploader.email,
                                       user=user,
                                       title=form.title.data,
                                       conference=conference.name)
                        i += 1
                # commit after loop
                paper.record_updated_time()

                try:
                    db.session.add(paper)
                    db.session.commit()
                except Exception:
                    db.session.rollback()
                    flash('Operation failed. Please try again or \
                          contact custom service',
                          'error')
                    return redirect(
                        url_for('paper.get_paper_info', paper_id=paper.id))
                flash('Successfully update paper information', 'info')
                add_event(current_user.full_name +
                          '(' + str(current_user.id) + ')' +
                          ' updated paper: (' + str(paper.id) + ') ' +
                          paper.title,
                          paper.to_json_log(),
                          conference_id=paper.conference_id,
                          paper_id=paper.id,
                          type='paper_update')
                return redirect(
                    url_for('paper.get_paper_info', paper_id=paper.id))
            else:
                flash(form.errors, 'error')
                return redirect(url_for('paper.edit_paper_info',
                                        paper_id=paper.id))
        # fill out the form
        form.title.data = paper.title
        form.abstract.data = paper.abstract
        form.keywords.data = paper.keywords
        form.comment.data = paper.comment
    return render_template('paper/paper_info_edit.html',
                           form=form, user=current_user, paper=paper,
                           submission_closed=False,
                           pdf_url=current_app.config['PDF_URL'],
                           allow_edit_author=allow_edit_author)
示例#34
0
def construct(object, form_fields):
    """
        Функция фабрика.
        Собирает форму по указанным параметрам
        Принимает:
            oject: Экземпляр класса формы
            form_fields(list[dicts]): Параметры формы. Список словарей
        Возвращает:
            Экземпляр класса формы
    """
    # Обойти список, добавить к экземпляру класса новые параметры
    # В свойства поля попадают следующие параметры
    # COLUMN_COMMENT, COLUMN_NAME, COLUMN_KEY, COLUMN_TYPE, IS_NULLABLE

    # Временная переменная для присвоения атрибутов поля формы
    # temp_field = None
    dynamic = WTFormsDynamicFields()

    for field in form_fields:
        label = field['COLUMN_COMMENT']

        # Если поле даты
        if field['COLUMN_TYPE'] == 'datetime':
            dynamic.add_field(field['COLUMN_NAME'], label, DateTimeField)
            # temp_field = DateTimeField(label=label)

        # Если поле числовое
        elif 'int' in field['COLUMN_TYPE']:
            dynamic.add_field(field['COLUMN_NAME'], label, IntegerField)
            # temp_field = IntegerField(label=label)

        # Все остальные просто текст пусть будут
        else:
            dynamic.add_field(field['COLUMN_NAME'], label, StringField)
            # temp_field = StringField(label=label)

        if field['IS_NULLABLE'] == 'YES':
            dynamic.add_validator(field['COLUMN_NAME'],
                                  DataRequired,
                                  message='Обязательное поле')
            # temp_field.validators=DataRequired()

        # Присвоить экземпляру класса новый атрибут
        # setattr(object, field['COLUMN_NAME'], temp_field)

        # object.__setitem__(field['COLUMN_NAME'], temp_field)

    object = dynamic.process(EditForm)
    # object.__setitem__('submit', SubmitField('Сохранить'))
    # setattr(object, 'submit', SubmitField('Сохранить'))

    return object
def test_long_field_name_replacement(setup):
    """ Test %% replacement with many fields
    Sets - Error situation.
    See if fields with many underscores and digits still
    get picked up correctly by the %field_name% formatter.
    Merely inducing an error to assert for correct field name replacement.
    """
    post = deepcopy(setup)
    post.add(u'a_very_long_10_field_name_1', '')
    post.add(u'yet_another_34_long_2_name_10_1', '')
    post.add(u'a_very_long_10_field_name_2', '')
    post.add(u'yet_another_34_long_2_name_10_2', '')

    dynamic_form = WTFormsDynamicFields()
    dynamic_form.add_field('a_very_long_10_field_name',
                           'A very long field name', TextField)
    dynamic_form.add_validator(
        'a_very_long_10_field_name',
        InputRequired,
        message=
        'Please fill in %a_very_long_10_field_name% or %yet_another_34_long_2_name_10%.'
    )
    dynamic_form.add_field('yet_another_34_long_2_name_10',
                           'A very long field name', TextField)
    dynamic_form.add_validator(
        'yet_another_34_long_2_name_10',
        InputRequired,
        message=
        'Please fill in %a_very_long_10_field_name% or %yet_another_34_long_2_name_10%.'
    )
    form = dynamic_form.process(SimpleForm, post)

    form.validate()

    assert form.validate() == False
    assert form.errors['a_very_long_10_field_name_1'] == [
        'Please fill in a_very_long_10_field_name_1 or yet_another_34_long_2_name_10_1.'
    ]
    assert form.errors['yet_another_34_long_2_name_10_1'] == [
        'Please fill in a_very_long_10_field_name_1 or yet_another_34_long_2_name_10_1.'
    ]
    assert form.errors['a_very_long_10_field_name_2'] == [
        'Please fill in a_very_long_10_field_name_2 or yet_another_34_long_2_name_10_2.'
    ]
    assert form.errors['yet_another_34_long_2_name_10_2'] == [
        'Please fill in a_very_long_10_field_name_2 or yet_another_34_long_2_name_10_2.'
    ]
    assert form.a_very_long_10_field_name_1(
    ) == '<input id="a_very_long_10_field_name_1" name="a_very_long_10_field_name_1" type="text" value="">'
    assert form.yet_another_34_long_2_name_10_1(
    ) == '<input id="yet_another_34_long_2_name_10_1" name="yet_another_34_long_2_name_10_1" type="text" value="">'
    assert form.a_very_long_10_field_name_2(
    ) == '<input id="a_very_long_10_field_name_2" name="a_very_long_10_field_name_2" type="text" value="">'
    assert form.yet_another_34_long_2_name_10_2(
    ) == '<input id="yet_another_34_long_2_name_10_2" name="yet_another_34_long_2_name_10_2" type="text" value="">'