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

Django-forms组件

时间:2019-10-04 23:17:48      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:长度   charset   input   nbsp   htm   info   显示   ensure   submit   

forms组件是用来干什么的?

1、校验数据;

2、页面显示错误信息;

3、渲染页面;

4、重置数据。

views.py中:

from django import forms

class BookForm(forms.Form):

    title = forms.CharField(max_length=32)
    price = forms.IntegerField()
    email = forms.EmailField()

其中,title、price、email是用来校验的字段。我们可以在Django Console中对它们进行校验:

 

Django Console:

#校验某个类下的字段,我们需要导入要校验的类
from
app01.views import BookForm
fm
=BookForm({"title":"yuan","price":123,"email":"123"})
fm.is_valid() # 合法返回True,不和法返回False False
fm.cleaned_data # 显示合法字段及其值(字典格式) {
title: yuan, price: 123}
fm.errors # 显示不合法字段及其值(字典格式) {
email: [Enter a valid email address.]} fm=BookForm({"title":"yuan","price":123,"email":"123@qq.com"}) fm.is_valid() True fm.cleaned_data {title: yuan, price: 123, email: 123@qq.com} fm.errors {}
fm
=BookForm({"title":"yuan","price":123,"email":"123@qq.com","abc":123}) # 只要需要校验的字段是合法的,那就是合法的,加其他内容无所谓 fm.is_valid() True fm.cleaned_data {title: yuan, price: 123, email: 123@qq.com} fm.errors {} fm=BookForm({"title":"yuanhfdurhgdjfhdfruhfugfhrfherjhfeuhuerhtu","price":123,"email":"123@qq.com","abc":123}) fm.is_valid() False fm.cleaned_data {price: 123, email: 123@qq.com} fm.errors {title: [Ensure this value has at most 32 characters (it has 42).]}

 

登录示例:

  1.用户名长度不能低于5位;

  2.密码必须是纯数字;

  3.邮箱必须符合邮箱格式;

  4.如果输入数据格式有问题,显示给用户。

 

首先,在数据库中创建一张表(用于存取合格数据)

models.py:

class UserInfo(models.Model):
    user=models.CharField(max_length=32)
    pwd=models.CharField(max_length=32)
    email=models.CharField(max_length=32)

 

发送http://127.0.0.1:8000/reg/请求:

urls.py:

from app01 import views
urlpatterns = [
    path(admin/, admin.site.urls),
    path(reg/, views.reg),
]

views.py:

from django import forms
from app01.models import UserInfo

class UserForm(forms.Form):
    msg={"required":"该字段不能为空"}
    user=forms.CharField(min_length=5, error_messages=msg)
    pwd=forms.IntegerField(error_messages=msg)
    email=forms.EmailField(error_messages=msg)

def reg(request):

    if request.method=="POST":
        print(request.POST)

        # 数据校验
        form=UserForm(request.POST)
        if form.is_valid():
            print(form.cleaned_data)
            UserInfo.objects.create(**form.cleaned_data)
            return HttpResponse("ok")
        else:
            # print(form.cleaned_data)
            # print(form.errors)  # {"user":["",""]}
            # print(form.errors.get("user"))
            # print(form.errors.get("user")[0])

            errors=form.errors
            return render(request, "reg.html", {"errors":errors})
    else:
        return render(request, "reg.html")

reg.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    .error{
        color: red;
        margin-left: 12px;
    }
</style>
<body>

<form action="" method="post">
    {% csrf_token %}
    <p>用户名 <input type="text" name="user"><span class="error">{{ errors.user.0 }}</span></p>
    <p>密码 <input type="text" name="pwd"><span class="error">{{ errors.pwd.0 }}</span></p>
    <p>邮箱 <input type="text" name="email"><span class="error">{{ errors.email.0 }}</span></p>
    <input type="submit">
</form>

</body>
</html>

 

Django-forms组件

标签:长度   charset   input   nbsp   htm   info   显示   ensure   submit   

原文地址:https://www.cnblogs.com/897463196-a/p/11623336.html

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