簡體   English   中英

使用wtforms驗證FileField

[英]Validating FileField using wtforms

我試圖驗證FileField從wtforms領域,但是,我得到下面的異常時,選擇文件時:

File "forms.py", line 15, in check_cover # my forms.py file with custom validator
  if field.data:
File "/usr/lib/python3.3/cgi.py", line 637, in __len__
  return len(self.keys())
File "/usr/lib/python3.3/cgi.py", line 626, in keys
  raise TypeError("not indexable")

驗證器代碼和表單本身:

def check_cover(form, field):
  if field.data: # this line raises exception
    filename = field.data.filename
    ext = os.path.splitext(filename)[1].strip(".")
    if not ext.lower() in ALLOWED_IMG_EXT:
        raise validators.ValidationError('Has to be an image')
  else:
    raise validators.ValidationError('Please, provide an image')

class BlogPostForm(Form):
  title = TextField('Title',
                    validators=[validators.Length(min=1, max=200)])
  content = TextAreaField('Content', [validators.Length(min=1)],
                          id='blog-content')
  cover_pic = FileField('Cover image', validators=[check_cover])

和HTML形式:

<form method="POST" action="save" enctype="multipart/form-data">
  {{ form.title }}
  {{ form.content }}
  {{ form.cover_pic }}
  <input type="submit" value="Save" />
</form>

當沒有選擇文件時,Validator適用於該情況,但是一旦我選擇了一個文件,它就會在該檢查中失敗。 我可以嘗試訪問filename ,而不僅僅是datafield.data.filename ),它工作正常,但只有實際選擇了文件。 如果沒有選擇文件,則會因AttributeError: 'bytes' object has no attribute 'value'而失敗AttributeError: 'bytes' object has no attribute 'value' 這是可以理解的。

可能是因為我使用的是python3嗎? 我該如何解決這個問題?

謝謝,
Rapolas

首先,您應該檢查是否選擇了文件:

if type(form.cover_pic.data) is not UnicodeType:

此外,使用strip方法而不是split時出錯:

ext = os.path.splitext(filename)[1].strip(".")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM