2013-07-04 28 views
1

我的Django的代碼此示例:爲什麼在模板呈現時django form.as_p調用form.clean方法?

# 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> 

當我發送get請求到這個文件我有這樣的輸出控制檯:

前渲染
init
in clean

當我寫{{form.text}},而不是{{form.as_p}}我只:

渲染
初始化

它接縫我之前as_p方法調用乾淨()在渲染模板的過程中。 在此之前,我提到as_p方法只是某種快捷方式(我知道它是Form類的一個方法),並沒有實現邏輯。
爲什麼會發生?它是一個錯誤還是一些有用的功能? Django的== 1.5.1

回答

2

版本,據我可以在源Django的看到有一個_html_output輔助函數返回功能form.as_p()。如果有數據綁定到窗體(如您的),則調用BaseForm類屬性錯誤。這個函數調用表單完全清理。所以我認爲這種行爲是故意渲染表單錯誤的。

0

的問題是,我unproper初始化形式,我應該使用Form(initial={#something#})

2

改變你的看法是這樣的:

# 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()將不再被稱爲

+0

感謝,我understend哪裏問題是 – kharandziuk

+0

上面要注意的基本問題是,如果請求不是使用POST創建的,則在TestForm構造函數中分配給** initial = **參數。如果明確規定,這應該被標記爲答案。 –