为什么django form.as_p在渲染模板时调用form.clean方法? [英] Why django form.as_p call form.clean method when template renders?
问题描述
我有这个django代码示例:
I have this sample of django code:
# views.py
def test_view(request):
form = TestForm(
request.POST or { 'text': 'some text'},
)
data = {
'form': form,
}
print 'before rendering'
return render(request, 'test.html', data)
# forms.py
class TestForm(forms.Form):
text = forms.CharField()
def __init__(self, *args, **kwargs):
print 'init'
super(TestForm, self).__init__(*args, **kwargs)
def clean(self):
print 'in clean'
和此模板:
#test.html
<form id='test-form' method="post" action="some url" enctype="multipart/form-data">
{{ form.as_p }}
<input type="submit" value="Save"/>
</form>
当我向该文件发送获取请求时,我在控制台中有以下输出:
when i send get request to this file i have this output in console:
在呈现
init
干净之前
before rendering
init
in clean
当我写{{form.text}}而不是{{form.as_p}}时,我只有:
when I write {{ form.text }} instead of {{ form.as_p }} I have only:
渲染前
init
before rendering
init
在我看来,as_p方法在呈现模板的过程中内部调用了clean().
在此之前,我提到过as_p方法只是某种捷径(我知道这是Form类的一种方法),并且没有实现逻辑.
为什么会发生?是错误还是有用的功能?
It seams to me that as_p method calls clean() internally in process of rendering template.
Before that I mentioned that as_p method only is some kind of shortcut(I understand that it's a method of Form class) and doesn't realize logic.
Why does it happen? Is it a bug or some usefull feature?
Django的版本== 1.5.1
Version of Django==1.5.1
推荐答案
像这样更改视图:
# views.py
def test_view(request):
if request.POST:
form = TestForm(request.POST)
# this is usually used when there's an actual post request
# and in this block you do validation
else:
form = TestForm(initial={'somekey': 'somevalue'})
data = {
'form': form,
}
print 'before rendering'
return render(request, 'test.html', data)
和clean()
将不再被调用
这篇关于为什么django form.as_p在渲染模板时调用form.clean方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!