zoukankan      html  css  js  c++  java
  • Pyhton学习——Day60

    Form组件
    - form表单(验证;保留上次内容)
    -
    - Ajax(验证;无需上次内容)
    - 返回HttpResponse
    - 前端:跳转或错误信息


    1. Form组件扩展:

    1.简单扩展
    利用Form组件自带的正则扩展:
    a. 方式一
    from django.forms import Form
    from django.forms import widgets
    from django.forms import fields
    from django.core.validators import RegexValidator

    class MyForm(Form):
    user = fields.CharField(
    error_messages={'invalid': '...'},
    validators=[RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^159[0-9]+$', '数字必须以159开头')],
    )
    b. 方式二
    from django.forms import Form
    from django.forms import widgets
    from django.forms import fields
    from django.core.validators import RegexValidator

    class MyForm(Form):
    user = fields.RegexField(r'^[0-9]+$',error_messages={'invalid': '...'})

    2.基于源码流程
    a. 单字段
    from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
    class AjaxForm(forms.Form):
    username = fields.CharField()
    user_id = fields.IntegerField(
    widget=widgets.Select(choices=[(0,'alex'),(1,'刘皓宸'),(2,'杨建'),])
    )
    # 自定义方法 clean_字段名
    # 必须返回值self.cleaned_data['username']
    # 如果出错:raise ValidationError('用户名已存在')
    def clean_username(self):
    v = self.cleaned_data['username']
    if models.UserInfo.objects.filter(username=v).count():
    # 整体错了
    # 自己详细错误信息
    raise ValidationError('用户名已存在')
    return v
    def clean_user_id(self):
    return self.cleaned_data['user_id']


    b. 整体错误验证
    class AjaxForm(forms.Form):
    username = fields.CharField()
    user_id = fields.IntegerField(
    widget=widgets.Select(choices=[(0,'alex'),(1,'刘皓宸'),(2,'杨建'),])
    )
    # 自定义方法 clean_字段名
    # 必须返回值self.cleaned_data['username']
    # 如果出错:raise ValidationError('用户名已存在')
    def clean_username(self):
    v = self.cleaned_data['username']
    if models.UserInfo.objects.filter(username=v).count():
    # 整体错了
    # 自己详细错误信息
    raise ValidationError('用户名已存在')
    return v
    def clean_user_id(self):
    return self.cleaned_data['user_id']

    def clean(self):
    value_dict = self.cleaned_data
    v1 = value_dict.get('username')
    v2 = value_dict.get('user_id')
    if v1 == 'root' and v2==1:
    raise ValidationError('整体错误信息')
    return self.cleaned_data


    PS: _post_clean


    2. Django序列化
    a.对象
    b.字典
    c.元祖

    ===================================
    预习:
    Model操作补充:http://www.cnblogs.com/wupeiqi/articles/6216618.html
    Ajax全套: http://www.cnblogs.com/wupeiqi/articles/5703697.html
    上传文件

    博客示例:...

    Win a contest, win a challenge
  • 相关阅读:
    dedecms5.7百度主动推送(实时) 开发
    胆囊结石食物选择
    读《遥远的救世主》与观看电视剧天道
    cnn健康增胖和调理好身体
    Machine-wide Progress Telerik Fiddler installation has been found at ...Please, use that one or uninstall it ...
    鼻炎治疗之路(转载)
    学医后才知道的小知识...
    一点浩然气,千里快哉风(修炼孟子浩然之气)
    孟尝君的逆袭
    张小龙和张一鸣的对立统一
  • 原文地址:https://www.cnblogs.com/pandaboy1123/p/8915532.html
Copyright © 2011-2022 走看看