forms组件

forms组件的作用

1 渲染页面

2 校验数据

3 渲染错误

  

forms组件的使用方法

书写:

首先需要新建一个py文件,并导入模块

from django import forms

 

 再书写一个类继承forms.Form

class MyRegForm(forms.Form):

 

 书写字段:

username = forms.CharField(label='用户名', min_length=3, max_length=8,
                               error_messages={
                                   'required': '用户名不能为空',
                                   'min_length': '用户名最少3位',
                                   'max_length': '用户名最多8位'
                               },
                               widget=forms.widgets.TextInput(
                                   attrs={'class': 'form-control', 'placeholder': 'username'})
                               )

 

书写方法(用于数据校验):

 # 局部钩子 校验用户名 
 def clean_username(self):
        username = self.cleaned_data.get('username')
        is_exist = models.UserInfo.objects.filter(username=username)
        if is_exist:
            self.add_error('username', '用户名已存在')
        # 返回校验字段
        return username

# 全局钩子 校验两次密码是否一致
def clean(self):
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if not password == confirm_password:
            self.add_error('confirm_password', '两次密码不一致')
        # 返回校验字段数据(class类中所有书写的字段)
        return self.cleaned_data

 

使用:

在视图中使用:

# 首先需要导入自定义的forms组件
from xxx  import MyRegForm

# 渲染方式:
# 调用类生成对象返回给前端,让前端渲染页面
form_obj = MyRegForm()


# 校验方式:
# 将前端传入的数据传入校验
form_obj = MyRegForm(request.POST)

# 校验通过 返回True
if form_obj.is_valid():
    # 能够从form_obj获取所有字段数据保存
    clean_data = form_obj.cleaned_data

 

在模板中使用:

1 用 {{ form_obj }} 方法来使用

2 可以使用for循环

3 for 循环得到 form对象
   form.auto_id 得到id_字段名
   form.errors 得到 字段:【错误信息】

 

posted @ 2023-12-08 08:56  wellplayed  阅读(2)  评论(0编辑  收藏  举报