Django-forms组件

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>

 

转载于:https://www.cnblogs.com/897463196-a/p/11623336.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值