daniel__
daniel__

Reputation: 11845

Upload with wtforms - unexpected end of regular expression

I am trying this code from here docs

class Form(Form):
    image = FileField(u'Image File', validators=[Regexp(u'^[^/\\]\.jpg$')])

    def validate_image(form, field):
        if field.data:
            field.data = re.sub(r'[^a-z0-9_.-]', '_', field.data)

Here is the error:

Traceback (most recent call last):
  File "tornadoexample2-1.py", line 111, in <module>
    class Form(Form):
  File "tornadoexample2-1.py", line 119, in Form
    image = FileField(u'Image File', validators=[Regexp(u'^[^/\\]\.jpg$')])
  File "/usr/local/lib/python2.7/dist-packages/wtforms/validators.py", line 256, in __init__
    regex = re.compile(regex, flags)
  File "/usr/lib/python2.7/re.py", line 190, in compile
    return _compile(pattern, flags)
  File "/usr/lib/python2.7/re.py", line 242, in _compile
    raise error, v # invalid expression
sre_constants.error: unexpected end of regular expression

Any idea about what the problem?

Upvotes: 0

Views: 1412

Answers (1)

jbub
jbub

Reputation: 2665

The regexp in Regexp(u'^[^/\\]\.jpg$') is not quite good.

Try running this, you will get the same exception:

import re
re.compile(u'^[^/\\]\.jpg$')

You need to escape each \ slash twice inside the [] brackets.

So you can rewrite it as u'^[^/\\\\]\.jpg$' or as a raw string ur'^[^/\\]\.jpg$'.

Hope this helps.

Upvotes: 2

Related Questions