【问题标题】:Validate/clean a FileField on a non-model form in Django?在 Django 中验证/清理非模型表单上的 FileField?
【发布时间】:2011-04-22 12:02:06
【问题描述】:

我最终试图通过扩展类型验证 FileField。但我什至无法获得该字段的干净方法来获取 POSTed 值。

from django.forms.forms import Form
from django.forms.fields import FileField
from django.forms.util import ValidationError

class TestForm(Form):        
    file = FileField(required=False)

    def clean_file(self):
        value = self.cleaned_data["file"]
        print "clean_file value: %s" % value
        return None     

@localhost
def test_forms(request):
    form = TestForm()    
    if request.method == "POST":
        form = TestForm(request.POST)        
        if form.is_valid():
            print "form is valid"
    return render_to_response("test/form.html", RequestContext(request, locals()))

当我运行代码时,我得到以下输出:

clean_file value: None
form is valid

也就是说,clean_file 方法无法获取文件数据。同样,如果它返回 None,则表单仍然有效。

这是我的表单 html:

<form enctype="multipart/form-data" method="post" action="#">
   <input type="file" id="id_file" name="file">
   <input type="submit" value="Save">
</form>

我已经看到 couple snippetssolutions 解决这个问题,但我无法让它们使用非模型表单。它们都声明了自定义字段类型。当我这样做时,我会遇到同样的问题;调用 super() 返回一个 None 对象。

【问题讨论】:

  • 仅供参考 - 我确实在 request.FILES 中看到了 InMemoryUploadFile 对象。

标签: django django-forms django-validation


【解决方案1】:

当您在帖子中实例化它时,您没有将request.FILES 传递到表单中。

 form = TestForm(request.POST, request.FILES)

the documentation

另请注意,您在 POST 上两次实例化表单,这是不必要的。将第一个移到函数末尾的 else 子句中(与 if request.method == 'POST' 处于同一级别)。

【讨论】:

    猜你喜欢
    • 2019-06-21
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2017-06-14
    • 2012-12-22
    • 2012-02-22
    相关资源
    最近更新 更多