微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Django 拓展点

1. dispathch()

from django.views import View
class CBV(View):
    def dispatch(self, request, *args, **kwargs):
        res = super(CBV, self).dispatch(request, **kwargs)
        return res

2. Form组件

2.1  单独字段验证    Form中is_valid()   full_clean()    self._clean_fields()

from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import HttpResponse
from django import formsfrom django.forms import fieldsfrom django.forms import widgetsfrom 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,'tom'),(2,'lily'),])
    )
    # 自定义方法 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):
        if models.UserInfo.objects.filter(id=self.cleaned_data['user_id']).count():
            raise ValidationError('用户id存在')
        return self.cleaned_data['user_id']
def ajax(request):
    if request.method == 'GET':
        obj = AjaxForm()
        return render(request,'ajax.html',{'obj':obj})
    else:
        ret = {'status':'杨建','message':None}
        import json        obj = AjaxForm(request.POST)
        if obj.is_valid():
            # 跳转百度
            # return redirect('http://www.baidu.com')
            # if ....
            #     obj.errors['username'] = ['用户名已经存在',]
            # if ....
            #     obj.errors['email'] = ['用户名已经存在',]
            ret['status'] = '钱'
            return HttpResponse(json.dumps(ret))
        else:
            # print(type(obj.errors))
            # print(obj.errors)
            from django.forms.utils import ErrorDict
            # print(obj.errors.as_ul())
            # print(obj.errors.as_json())
            # print(obj.errors.as_data())
            ret['message'] = obj.errors            # 错误信息显示页面上
            return HttpResponse(json.dumps(ret))
# -----------------------ajax.html----------------------
<body>
    <form id="fm" method="POST" action="/ajax/">
        {% csrf_token %}
        {{ obj.as_p }}
        <input type="button" value="Ajax提交" id="btn" />
    </form>
    <script src="/static/jquery-3.1.1.js"></script>
    <script>
        $(function () {
            $('#btn').click(function () {
                $.ajax({
                    url: '/ajax/',                    type: 'POST',                    data: $('#fm').serialize(),                    dataType: 'JSON',                    success:function (arg) {
                        // arg: 状态,错误信息
                        if (arg.status == '钱'){
                            window.location.href = "http://www.baidu.com"
                        }
                        console.log(arg);
                    }
                })
            })
        })
    </script>
</body>

2.2  整体字段验证    Form中is_valid()   full_clean()    self._clean_form()

#--------------------------------------views.py--------------------------------------
from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import HttpResponse
from django import formsfrom django.forms import fieldsfrom django.forms import widgetsfrom django.core.exceptions import NON_FIELD_ERRORS,'linly'),])
    )
    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
def ajax(request):
    if request.method == 'GET':
        obj = AjaxForm()
        return render(request,{'obj':obj})
    else:
        obj = AjaxForm(request.POST)
        if obj.is_valid():
        
# -----------------------ajax.html----------------------
<body>
    <form id="fm" method="POST" action="/ajax/">
        {% csrf_token %}
        {{ obj.as_p }}
        <input type="button" value="Ajax提交" id="btn" />
    </form>
    <script src="/static/jquery-3.1.1.js"></script>
    <script>
        $(function () {
            $('#btn').click(function () {
                $.ajax({
                    url: '/ajax/',                    success:function (arg) {
                        // arg: 状态,错误信息
                        if (arg.status == '钱'){
                            window.location.href = "http://www.baidu.com"
                        }
                        console.log(arg);
                    }
                })
            })
        })
    </script>
</body>

2.3  自定义功能        

Form中is_valid()  full_clean()     selef._post_clean


版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐