Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deform File Upload overrides my error message with Invalid pstruct: not a FieldStorage instance

If I do not select a file and just click 'submit', I get the following error:-

Invalid pstruct: {'upload': "b'' is not a FieldStorage instance"}

This is not the behavior I get on the deform demo site where leaving it empty results in the more reasonable 'Required' error message.

Using my own validator as below does not solve the issue:-

def validate_file(node, value, **kwargs):
    if not value:
        raise colander.Invalid(node, "Please select a file")

class Schema(colander.MappingSchema):
    excel_file = colander.SchemaNode(deform.FileData(),
            widget=deform.widget.FileUploadWidget(tmpstore),
            validator=validate_file)

I can see that the error is raised, but the output of e.render() where e is the ValidationFailure from form.validate does not match the error itself. The relevant deform source code is in 'widget.py' where the _FieldStorage class checks whether cstruct has a file attribute and raises it's own Invalid exception.

Here's the function which does the validation call (bog standard stuff really), which returns the rendered page.

def generate_upload_form(request):
    form = deform.Form(upload_schema, buttons=('submit',))
    if getattr(request, 'POST') and 'submit' in request.POST:
        try:
            value_dict = form.validate(request.POST.items())
        except deform.ValidationFailure as e:  # Invalid form
            form = e.render()
        else:  # Successfully validated, now do operation
            upload_form_operation(request, value_dict)
    if isinstance(form, deform.Form):
        form = form.render()
    return form

How do I show my own error message without monkey-patching the deform codebase?

like image 836
Ng Oon-Ee Avatar asked Mar 13 '17 09:03

Ng Oon-Ee


1 Answers

Are you sure you are actually submitted the form data correctly? This error normally happens when deform attempts to deserialize the submitted value via duck typing.

One particular item that get's overlooked is to make sure your HTML form has the additional enctype define e.g.

 enctype="multipart/form-data"

Without this the form submits the filename as a string which will then fail

like image 145
Mr-F Avatar answered Sep 30 '22 20:09

Mr-F