Django form

Posted gaizhongfeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django form相关的知识,希望对你有一定的参考价值。

Django form 使用步骤:
        1.创建模板          class LoginForm(forms.Form) ....
        2.创建模板对象,将请求传给模板  obj = LoginForm(req.POST)
        3.验证       obj.is_valid():
        4.获取正确信息/错误信息  正确信息:obj.clean()  错误信息:obj.errors

 

views:

from django.core.exceptions import ValidationError
from django.core.serializers import json
from django.http import HttpResponse
from django.shortcuts import render
from django import  forms
# Create your views here.

# 定义模板
class LoginForm(forms.Form):
    #html 标签name相对应
    user = forms.CharField(min_length=6,error_messages={"required":"用户名不能为空","min_length":"长度不能小于6"})
    pwd = forms.CharField(min_length=6)


def test(req):
    print(req.POST.get(pwd))
    return render(req,login.html)


def login(req):
    if req.method == "GET":
        obj = LoginForm()
        return render(req, login.html,{obj:obj})
    elif req.method == "POST":
        ‘‘‘
           # 模板会去取post中的值
        obj = LoginForm( req.POST)
            #验证
        status = obj.is_valid()
        print(status)

            #拿到验证通过的值
        value = obj.clean()
        print(value)
        #获取错误的值obj.errors
        error_obj=obj.errors.as_json()
        print(error_obj)
        ‘‘‘
        obj = LoginForm(req.POST)
        if  obj.is_valid():
            value = obj.clean()
            print(value)
            # create(**value)
        else:
            error_obj = obj.errors
            #拿到user 的错误信息
            print(error_obj[user][0])
        return render(req, login.html,{obj:obj})

    #ajax
        #return HttpResponse(req,cls=JsonCustomeEncoder)

class JsonCustomeEncoder(json.DjangoJSONEncoder):
        def default(self,field):
            if isinstance(field,ValidationError):
                return {code:field.code,message:field.message}
            else:
                return json.DjangoJSONEncoder.default(self,field)

 

 

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/login.html" method="post">
    user:{{ obj.user }}<input type="text" name="user"/>
    <span>{{ obj.errors.user.0}}</span>
    password:{{ obj.pwd }} <input type="text" name="pwd">
     <span>{{ obj.errors.pwd.0}}</span>
    <input type="submit" value="提交">
    <input type="button" id="ajax_submit" value="ajax_submit">
</form>


<script src="/static/jquery-2.1.4.min.js"></script>
<script>
    $(function () {
        $(#ajax_submit).click(function () {
            $.ajax({
                url:"login.html",
                data: {user:root,pwd:123},
                type:"POST",
                success:function (arg) {
                    
                }
            });
        });
    })
</script>

</body>
</html>

 

以上是关于Django form的主要内容,如果未能解决你的问题,请参考以下文章

django认证 auth

Django进阶

Django之Form功能

转 Django中的Form

python-- Django Form

Django的请求生命周期与中间件中的5中方法