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

djangoform详解

时间:2018-03-17 10:57:06      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:属性   put   too   html 表单   字段   pen   inpu   使用   对象   

orm表单的功能

  • 准备数据、重构数据,以便下一步提交。
  • 为数据创建HTML 表单
  • 接收并处理客户端提交的表单和数据

普通字段详解:

技术分享图片 布尔值 checkbox
技术分享图片 charFied input()
技术分享图片 ChoiceField (select标签)
技术分享图片 DateField Dateinput 标签
技术分享图片 emailField EaillInput
技术分享图片 FileField
技术分享图片 ImageField
技术分享图片 MultipleChoiceField (select标签 multiple)

处理关系的字段:

两个字段可用于表示模型之间的关系:ModelChoiceFieldModelMultipleChoiceField这两个字段都需要单个queryset参数,用于创建字段的选择。

技术分享图片 ModelChoiceField
技术分享图片 ModelMultipleChoiceField

表单里choice用的数据库里数据时不会实时更新。所以需要将choice放到init里,每次使用都执行一遍:

技术分享图片 示例

字段的核心参数:

required

   f = forms.CharField(required=False)
  默认为True。

label

技术分享图片
>>> from django import forms
>>> class CommentForm(forms.Form):
...     name = forms.CharField(label=‘Your name‘)
...     url = forms.URLField(label=‘Your Web site‘, required=False)
...     comment = forms.CharField()
>>> f = CommentForm(auto_id=False)
>>> print(f)
<tr><th>Your name:</th><td><input type="text" name="name" /></td></tr>
<tr><th>Your Web site:</th><td><input type="url" name="url" /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
技术分享图片

error_messages:

error_messages 参数让你覆盖字段引发的异常中的默认信息。传递的是一个字典,其键为你想覆盖的错误信息

has_changed():方法用于决定字段的值是否从初始值发生了改变。返回True 或False

字段数据:

不管表单提交的是什么数据,一旦通过调用is_valid() 成功验证(is_valid() 返回True),验证后的表单数据将位于form.cleaned_data 字典中。

技术分享图片
from django.core.mail import send_mail

if form.is_valid():
    subject = form.cleaned_data[‘subject‘]
    message = form.cleaned_data[‘message‘]
    sender = form.cleaned_data[‘sender‘]
    cc_myself = form.cleaned_data[‘cc_myself‘]

    recipients = [‘info@example.com‘]
    if cc_myself:
        recipients.append(sender)

    send_mail(subject, message, sender, recipients)
    return HttpResponseRedirect(‘/thanks/‘)
技术分享图片

重写验证方法:

技术分享图片
  # 自定义方法(局部钩子),密码必须包含字母和数字
  def clean_password(self):
      if self.cleaned_data.get(‘password‘).isdigit() or self.cleaned_data.get(‘password‘).isalpha():
          raise ValidationError(‘密码必须包含数字和字母‘)
      else:
          return self.cleaned_data[‘password‘]
 
  def clean_valid_code(self):  # 检验验证码正确;之前生成的验证码保存在了了session中
      if self.cleaned_data.get(‘valid_code‘).upper() == self.request.session.get(‘valid_code‘):
          return self.cleaned_data[‘valid_code‘]
      else:
          raise ValidationError(‘验证码不正确‘)
 
  # 自定义方法(全局钩子, 检验两个字段),检验两次密码一致;
  def clean(self):
      if self.cleaned_data.get(‘password‘) != self.cleaned_data.get(‘password2‘):
          raise ValidationError(‘密码不一致‘)
      else:
          return self.cleaned_data
 
  # 注意,上面的字典取值用get, 因为假如在clean_password中判断失败,那么没有返回值,最下面的clean方法直接取值就会失败s 
技术分享图片

使用表单模:

  • {{ form.as_table }} 以表格的形式将它们渲染在<tr> 标签中
  • {{ form.as_p }}  将它们渲染在<p> 标签中
  • {{ form.as_ul }} 将它们渲染在<li> 标签中

手工渲染字段:{{ form.name_of_field }

技术分享图片
技术分享图片
{{ form.non_field_errors }}
<div class="fieldWrapper">
    {{ form.subject.errors }}
    <label for="{{ form.subject.id_for_label }}">Email subject:</label>
    {{ form.subject }}
</div>
<div class="fieldWrapper">
    {{ form.message.errors }}
    <label for="{{ form.message.id_for_label }}">Your message:</label>
    {{ form.message }}
</div>
<div class="fieldWrapper">
    {{ form.sender.errors }}
    <label for="{{ form.sender.id_for_label }}">Your email address:</label>
    {{ form.sender }}
</div>
<div class="fieldWrapper">
    {{ form.cc_myself.errors }}
    <label for="{{ form.cc_myself.id_for_label }}">CC yourself?</label>
    {{ form.cc_myself }}
</div>
技术分享图片

渲染表单的错误信息:{{ form.name_of_field.errors }}

迭代表单的字段{{ field }} 包含所有有用的属性

技术分享图片
{% for field in form %}
    <div class="fieldWrapper">
        {{ field.errors }}
        {{ field.label_tag }} {{ field }}
    </div>
{% endfor %}
技术分享图片

可重用的表单模板:

在表单保存到单独的模块,用includ标签来重用

技术分享图片
{% include "form_snippet.html" %}

# In form_snippet.html:
{% for field in form %}
    <div class="fieldWrapper">
        {{ field.errors }}
        {{ field.label_tag }} {{ field }}
    </div>
{% endfor %}
技术分享图片

widgets窗口小部件 

widgets.attr 设置标签属性

技术分享图片
class CommentForm(forms.Form):
    name = forms.CharField(widget=forms.TextInput(attrs={‘class‘: ‘special‘}))
    url = forms.URLField()
    comment = forms.CharField(widget=forms.TextInput(attrs={‘size‘: ‘40‘}))


>>> f = CommentForm(auto_id=False)
>>> f.as_table()
<tr><th>Name:</th><td><input type="text" name="name" class="special"/></td></tr>
<tr><th>Url:</th><td><input type="url" name="url"/></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" size="40"/></td></tr
技术分享图片
生成form field对象,指定类型
from django.form impor widgets,fields

xxxx = fields.CharField(widget=widgets.Textarea)
 
 

djangoform详解

标签:属性   put   too   html 表单   字段   pen   inpu   使用   对象   

原文地址:https://www.cnblogs.com/xc1234/p/8587320.html

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