码迷,mamicode.com
首页 > 其他好文 > 详细

django form

时间:2015-08-25 14:19:03      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:django   python   

django form

1. 继承form类

from django import forms
class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    email = forms.EmailField(required=False)
    message = forms.CharField()

主要是继承forms.Form ,写法跟models 里面的差不多。
完了之后你可以构造出一个实例。
f = ContactForm()
form类有很多实用的方法,比如说

  • Form.has_changed() 判断是否变化了
  • Form.cleaned_data
  • Form.is_valid() 判断是否valid
  • Form.as_p() html 里面的p来隔开每个field
  • Form.as_ul()

form api详细可见官网 :
https://docs.djangoproject.com/en/1.8/ref/forms/api/

2. view

步骤是

  1. 绑定POST
  2. 判断是否有效,用is_valid()
  3. 取数据,用cleaned_data ,他是一个字典类型数据。
  4. 然后再调用函数,这里是发邮件。
def contact(request):
    if request.method == ‘POST‘:
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            send_mail(
                cd[‘subject‘],
                cd[‘message‘],
                cd.get(‘email‘, ‘noreply@example.com‘),
                [‘siteowner@example.com‘],
            )
            return HttpResponseRedirect(‘/contact/thanks/‘)
    else:
        form = ContactForm()
    return render(request,‘contact_form.html‘, {‘form‘: form})

如果是get请求,则重新创建一个form对象,然后渲染。

3.模板

<html>
<head>
    <title>Contact us</title>
</head>
<body>
    <h1>Contact us</h1>

    {% if form.errors %}
        <p style="color: red;">
            Please correct the error{{ form.errors|pluralize }} below.
        </p>
    {% endif %}

    <form action="" method="post">
        <table>
            {{ form.as_table }}
        </table>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

这里调用了form.as_table生成 表格形式的表单,默认他是全部在一行上面的。

版权声明:本文为博主原创文章,未经博主允许不得转载。

django form

标签:django   python   

原文地址:http://blog.csdn.net/aca_jingru/article/details/47975475

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!