Pylons FormEncode with an array of form elements

前端 未结 2 1106
醉酒成梦
醉酒成梦 2021-02-06 19:00

I have a Pylons app and am using FormEncode and HtmlFill to handle my forms. I have an array of text fields in my template (Mako)

  
    Yardage&l         


        
相关标签:
2条回答
  • 2021-02-06 19:34

    Turns out what I wanted to do wasn't quite right.

    Template:

    <tr>
      <td>Yardage</td>
      % for hole in range(9):
      <td>${h.text('hole-%s.yardage'%(hole), maxlength=3, size=3)}</td>
      % endfor
    </tr>
    

    (Should have made it in a loop to begin with.) You'll notice that the name of the first element will become hole-1.yardage. I will then use FormEncode.variabledecode to turn this into a dictionary. This is done in the

    Schema:

    import formencode
    
    class HoleSchema(formencode.Schema):
        allow_extra_fields = False
        yardage = formencode.validators.Int(not_empty=True)
        par = formencode.validators.Int(not_empty=True)
    
    class CourseForm(formencode.Schema):
        allow_extra_fields = True
        filter_extra_fields = True
        name = formencode.validators.NotEmpty(messages={'empty': 'Name must not be empty'})
        hole = formencode.ForEach(HoleSchema())
    

    The HoleSchema will validate that hole-#.par and hole-#.yardage are both ints and are not empty. formencode.ForEach allows me to apply HoleSchema to the dictionary that I get from passing variable_decode=True to the @validate decorator.

    Here is the submit action from my

    Controller:

    @validate(schema=CourseForm(), form='add', post_only=False, on_get=True, 
              auto_error_formatter=custom_formatter,
              variable_decode=True)
    def submit(self):
        # Do whatever here.
        return 'Submitted!'
    

    Using the @validate decorator allows for a much cleaner way to validate and fill in the forms. The variable_decode=True is very important or the dictionary will not be properly created.

    0 讨论(0)
  • 2021-02-06 19:49
    c.form_result = schema.to_python(request.params) - (without dict)
    

    It seems to works fine.

    0 讨论(0)
提交回复
热议问题