`
huangyiiiiii
  • 浏览: 118547 次
  • 性别: Icon_minigender_1
最近访客 更多访客>>
社区版块
存档分类
最新评论

newforms 太好用了

阅读更多
建一个项目 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)
标题:
作者:"text" name="author" maxlength="20" />
内容:

In [6]: print form.as_ul()
  • 标题:

  • 作者: "author" maxlength="20" />

  • 内容:


  • 一个空白的 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)
    标题:
    作者:"text" name="author" value="huangyi" maxlength="20" />
    内容:

    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'
    分享到:
    评论
    3 楼 simohayha 2007-05-23  
    贴代码用bbcode比较好,richcode不好用.
    2 楼 huangyiiiiii 2007-05-23  
    http://codeplayer.blogspot.com/2007/05/newforms.html
    1 楼 huangyiiiiii 2007-05-23  
    郁闷那,我都是写的 &lt; &gt; ,怎么都当html显示出来了呢?

    相关推荐

    Global site tag (gtag.js) - Google Analytics