Django之forms组件

Posted wualin

tags:

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

校验字段功能:

index.html

<form action="" method="post">
    {% csrf_token %}
    <p>用户名<input type="text" name="username"></p>
    <p>密码<input type="password" name="password"></p>
    <p>确认密码<input type="password" name="r_password"></p>
    <p>邮箱<input type="email" name="email"></p>
    <input type="submit">
</form>

views.py(forms暂时先放在views.py,为了程序可读性更高应新建一个.py文件)

from django import forms

# 先定义forms组件类
class UserForm(forms.Form):
    username = forms.CharField(min_length=6)
    password = forms.CharField(min_length=6)
    r_password = forms.CharField(min_length=6)
    email = forms.EmailField()


def index(request):
    if request.method == ‘POST‘:

        # 实例化form组件类的时候传入的参数要求:form表单name的属性必须与forms组件的字段名称相同
        form = UserForm(request.POST) #传入的是一个字典:{‘username‘:‘alexss}
        print(form.is_valid())# 布尔类型
        if form.is_valid(): # 判断是否校验成功(传入的参数规则能对应上类中的规则# )
            # 如果传入了一个类中没有定义的字段,则不会去进行校验,直接忽视
            print(form.cleaned_data) # 校验成功的字段放在该字典内
        else:
            print(form.changed_data) # 同样,校验成功的会在该字典内
            print(form.errors) # 校验失败的会放在该字典内,存放格式:字段名对应一个字段,字典内是错误信息
        return HttpResponse(‘OK‘)
    return render(request,‘index.html‘)

forms组件的渲染标签功能

方式1:

views.py

from django import forms

# 先定义forms组件类
class UserForm(forms.Form):
    username = forms.CharField(min_length=6)
    password = forms.CharField(min_length=6)
    r_password = forms.CharField(min_length=6)
    email = forms.EmailField()


def index(request):
    form = UserForm()
    return render(request,‘index.html‘,locals())

index.html

<form action="" method="post">
    <p>
        用户名{{ form.username }}
    </p>
    <p>
        密码{{ form.password }}
    </p>
    <p>
        确认密码{{ form.r_password }}
    </p>
    <p>
        邮箱{{ form.email }}
    </p>
    <input type="submit">
</form>

方式2:在views.py中定义字段可以添加label属性,在渲染标签时,默认的form.label是字段名,可以在定义form是设置label属性

views.py

from django import forms

# 先定义forms组件类
class UserForm(forms.Form):
    username = forms.CharField(min_length=6,label=‘用户名‘)
    password = forms.CharField(min_length=6,label=‘密码‘)
    r_password = forms.CharField(min_length=6,label=‘确认密码‘)
    email = forms.EmailField(label=‘密码‘)


def index(request):
    form = UserForm()
    return render(request,‘index.html‘,locals())

index.html

<h3>forms组件渲染标签方式2</h3>
<form action="" method="post">
    {% for filed in form %}
        <div>
            <label for="">{{ filed.label }}</label>
            {{ filed }}
        </div>
    {% endfor %}
    
    <input type="submit">
</form>

方式3:该方式不推荐使用,过于呆滞

<form action="" method="post">
    {{ form.as_p }}
    <input type="submit">
</form>

forms组件的渲染错误信息

<h3>form组件渲染标签方式1</h3>
<form action="" method="post">
    {% csrf_token %}
    <p>{{ form.username.label }}
        {{ form.username }} <span>{{ form.username.errors.0 }}</span>
    </p>
    <p>{{ form.password.label }}
        {{ form.password }} <span>{{ form.password.errors.0 }}</span>
    </p>
    <p>{{ form.r_password.label }}
        {{ form.r_password }} <span>{{ form.r_password.errors.0 }}</span>
    </p>
    <p>{{ form.email.label }}
        {{ form.email }} <span>{{ form.email.errors.0 }}</span>
    </p>
    <input type="submit">
</form>

最新版本的django好像不需要forms组件去渲染,在输入时会自动进行校验,假如提交时不符合会弹出提示

forms组件的参数配置

渲染时使密码输入框显示秘文

from django import forms
from django.forms import widgets
# 先定义forms组件类
class UserForm(forms.Form):
    username = forms.CharField(min_length=6,label=‘用户名‘)
    password = forms.CharField(min_length=6,label=‘密码‘,widget=widgets.PasswordInput())
    # 在定义类时添加widget属性=widgets.PasswordInput()
    r_password = forms.CharField(min_length=6,label=‘确认密码‘,widget=widgets.PasswordInput())
    email = forms.EmailField(label=‘密码‘)

渲染时给输入框添加样式类

class UserForm(forms.Form):
    username = forms.CharField(min_length=6,label=‘用户名‘,widget=widgets.TextInput(attrs={"class":"form-control"}))
    password = forms.CharField(min_length=6,label=‘密码‘,widget=widgets.PasswordInput(attrs={"class":"form-control"}))
    r_password = forms.CharField(min_length=6,label=‘确认密码‘,widget=widgets.TextInput(attrs={"class":"form-control"}))
    email = forms.EmailField(label=‘密码‘,widget=widgets.TextInput(attrs={"class":"form-control"}))

forms组件校验的局部钩子

验证用户名与邮箱用户名是否存在

class UserForm(forms.Form):
    username = forms.CharField(min_length=4,label=‘用户名‘,widget=widgets.TextInput(attrs={"class":"form-control"}))
    password = forms.CharField(min_length=4,label=‘密码‘,widget=widgets.PasswordInput(attrs={"class":"form-control"}))
    r_password = forms.CharField(min_length=4,label=‘确认密码‘,widget=widgets.TextInput(attrs={"class":"form-control"}))
    email = forms.EmailField(label=‘邮箱‘,widget=widgets.TextInput(attrs={"class":"form-control"}))
    
    def clean_username(self):
        val = self.cleaned_data.get(‘username‘)
        ret = UserInfo.objects.filter(username=val)
        if not ret:
            return val
        else:
            raise ValidationError("用户名已存在")
            
    def clean_email(self):
        val = self.cleaned_data.get(‘email‘)
        ret = UserInfo.objects.filter(email=val)
        if not ret:
            return val
        else:
            raise ValidationError("邮箱已存在")
            

forms组件校验的全局钩子

class UserForm(forms.Form):
    username = forms.CharField(min_length=4,label=‘用户名‘,widget=widgets.TextInput(attrs={"class":"form-control"}))
    password = forms.CharField(min_length=4,label=‘密码‘,widget=widgets.PasswordInput(attrs={"class":"form-control"}))
    r_password = forms.CharField(min_length=4,label=‘确认密码‘,widget=widgets.PasswordInput(attrs={"class":"form-control"}))
    email = forms.EmailField(label=‘邮箱‘,widget=widgets.TextInput(attrs={"class":"form-control"}))
    
    # 全局钩子
    def clean(self):
        pwd1 = self.cleaned_data.get(‘password‘)
        pwd2 = self.cleaned_data.get(‘r_password‘)
        if pwd1 == pwd2:
            return self.cleaned_data
        else:
            raise ValidationError(‘两次密码输入不一致‘)

全局钩子捕获异常是使用form.error.get(‘all‘)

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

django之Form组件--ajax提交

Django之Form组件

Django之form组件

django之form组件cookiesession

Django之form组件

Django之Form组件