在 Django 中验证/清理非模型表单上的 FileField?
我最终尝试通过扩展类型验证 FileField。但我什至无法获取该字段的 clean 方法来获取 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>
我看到了 几个片段 与 此问题的解决方案,但我无法让它们与非 -模型形式。它们都声明了自定义字段类型。当我这样做时,我遇到了同样的问题;调用 super() 返回一个 None 对象。
I'm ultimately trying to validate a FileField by extension type. But I'm having trouble even getting the clean method for this field to pickup the POSTed value.
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()))
When I run the code, I'm getting the following output:
clean_file value: None
form is valid
In other words, the clean_file method is not able to get the file data. Likewise, if it returns None, the form is still valid.
Here is my form html:
<form enctype="multipart/form-data" method="post" action="#">
<input type="file" id="id_file" name="file">
<input type="submit" value="Save">
</form>
I have seen a couple snippets with solutions for this problem, but I cannot get them to work with a non-model form. They both declare a custom field type. When I do that, I get the same problem; calling super() returns a None object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您在帖子中实例化它时,您没有将
request.FILES
传递到表单中。请参阅文档。
另请注意,您在 POST 上实例化表单两次,这是不必要的。将第一个移动到函数末尾的 else 子句中(与
if request.method == 'POST' 处于同一级别
)。You're not passing
request.FILES
into the form when you instantiate it in the post.See the documentation.
Also note that you're instantiating the form twice on POST, which is unnecessary. Move the first one into an else clause at the end of the function (at the same level as
if request.method == 'POST'
).