建一个项目 newformstutorials ,建一个 app blog ,在 blog 的 models 中定义个:
class Article(models.Model): title = models.CharField(u'标题', maxlength=255) author = models.CharField(u'作者', maxlength=20) hits = models.IntegerField(u'点击数', default=0, editable=False) content = models.TextField(u'内容')配置好数据库,把 newformstutorials.blog 加到 INSTALLED_APPS,manage.py syncdb,然后 manage.py shell ,然后:
In [1]: import django.newforms as forms In [2]: from newformstutorials.blog.models import Article In [3]: ArticleForm = forms.form_for_model(Article) In [4]: form = ArticleForm() In [5]: print unicode(form) <tr><th><label for="id_title">标题:</label></th><td><input id="id_title" type="t ext" name="title" maxlength="255" /></td></tr> <tr><th><label for="id_author">作者:</label></th><td><input id="id_author" type= "text" name="author" maxlength="20" /></td></tr> <tr><th><label for="id_content">内容:</label></th><td><textarea id="id_content" rows="10" cols="40" name="content"></textarea></td></tr> In [6]: print form.as_ul() <li><label for="id_title">标题:</label> <input id="id_title" type="text" name="t itle" maxlength="255" /></li> <li><label for="id_author">作者:</label> <input id="id_author" type="text" name= "author" maxlength="20" /></li> <li><label for="id_content">内容:</label> <textarea id="id_content" rows="10" co ls="40" name="content"></textarea></li>一个空白的 form 就这样出来了,这就是个添加文章的表单,让我们用这个表单来加点数据吧:
In [7]: form = ArticleForm({'title':'some title','author':'huangyi'}) In [8]: form.is_valid() Out[8]: False In [9]: form.errors Out[9]: {'content': [u'This field is required.']} In [10]: form = ArticleForm({'title':'some title','author':'huangyi', 'content': 'some contents...'}) In [11]: form.is_valid() Out[11]: True In [12]: article = form.save(commit=True)OK,数据就这样保存了,我们再来试试数据更新的页面吧:
In [13]: ChangeForm = forms.form_for_instance(article) In [14]: form = ChangeForm() In [15]: print unicode(form) <tr><th><label for="id_title">标题:</label></th><td><input id="id_title" type="t ext" name="title" value="some title" maxlength="255" /></td></tr> <tr><th><label for="id_author">作者:</label></th><td><input id="id_author" type= "text" name="author" value="huangyi" maxlength="20" /></td></tr> <tr><th><label for="id_content">内容:</label></th><td><textarea id="id_content" rows="10" cols="40" name="content">some contents...</textarea></td></tr> In [16]: form = ChangeForm({'title':'another title', 'author':'huangyi', 'conten t':'other contents...'}) In [17]: form.is_valid() Out[17]: True In [18]: form.save() Out[18]: <Article: Article object> In [19]: article = Article.objects.get(id=article.id) In [20]: article.title Out[20]: 'another title'