Cha*_*ert 4 django django-forms django-validation
我最终试图通过扩展类型验证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()))
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,我得到以下输出:
clean_file value: None
form is valid
Run Code Online (Sandbox Code Playgroud)
换句话说,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>
Run Code Online (Sandbox Code Playgroud)
我已经看到了几个片段与解决方案对于这个问题,但我不能让他们与非模型的形式工作.它们都声明了自定义字段类型.当我这样做时,我遇到同样的问题; 调用super()返回一个None对象.
request.FILES当您在帖子中实例化它时,您不会传入表单.
form = TestForm(request.POST, request.FILES)
Run Code Online (Sandbox Code Playgroud)
请参阅文档.
另请注意,您在POST时将表单实例化两次,这是不必要的.将第一个移动到函数末尾的else子句中(与同一级别if request.method == 'POST').
| 归档时间: |
|
| 查看次数: |
4115 次 |
| 最近记录: |