最近在項(xiàng)目上用到了 Django 的自帶的 Form 表單,遇到了一些坑,今天給大家出的這篇 Python基礎(chǔ)教程 也是做了一個(gè)簡(jiǎn)單的總結(jié),大家可以對(duì)號(hào)出坑。
Form 基礎(chǔ)介紹
首先讓我們先來(lái)了解下 Django 中 Form 表單的基本用法。Django 中提供了兩種 Form 表單類(lèi)型,一種是 forms.Form ,另外一種是 forms.ModelForm 。很明顯,一種是普通的 Form 表單類(lèi)型,另外一種是和 Model 有關(guān)聯(lián)的表單類(lèi)型。官方文檔中是這樣來(lái)介紹 ModelForm 的:
If you’re building a database-driven app, chances are you’ll have forms that map closely to Django models. For instance, you might have a BlogComment model, and you want to create a form that lets people submit comments. In this case, it would be redundant to define the field types in your form, because you’ve already defined the fields in your model.
For this reason, Django provides a helper class that lets you create a Form class from a Django model.