Django框架学习日寄(四)——Form&ModelForm

Django框架学习日寄(四)——Form&ModelForm

Form/ModelForm组件

极大地方便表单的展示及数据的获取及校验.

功能包括且不限于:

  • 用户提交数据校验
  • 错误提示
  • 填错无需再重新填表(保留上次填表数据)
  • 关联数据,前端方便实现循环展示

Form

后端使用:

# views.py
class MyForm(Form):
	user = forms.CharField(weidget=forms.Input)
    pwd = forms.CharField(weidget=forms.Input)
    email = forms.CharField(weidget=forms.Input)
    
def user_add(request):
    if request.method == "GET":
        form = MyForm()
        return render(request, "user_add.html", {"form":form})

前端可以这么使用form组件:

<!-- user_add.html -->
<form method="post">
    {% for field in form %}
    	{{ field }}
    {% endfor %}
</form>

<form method="post">
    {{% form.user %}}
    {{% form.pwd %}}
    {{% form.emal %}}
</form>

如果表单中包含URLFieldEmailField和其他整数字段类似,Django将使用url、email和number这样的HTML5输入类型。默认情况下,浏览器可能会对这些字段进行他们自身的验证,这些验证可能比Django的验证更严格。如果你想禁用这个行为,请设置form标签的novalidate属性,或者制定一个不同的字段,如TextInput

ModelForm(推荐使用)

更加简化流程.

# models.py
class UserInfo(models.Model):
    """用户信息表"""
    name = models.CharField(verbose_name="用户名", max_length=32)
    password = models.CharField(verbose_name="密码", max_length=64)
    age = models.IntegerField(verbose_name="年龄", default=0)

    def __str__(self):
        return self.name

# views.py
class UserInfoModelForm(forms.ModelForm):
    class Meta:
        model = UserInfo  # 与models建立了依赖关系
        fields = "__all__"
        
def user_add(request):
    if request.method == "GET":
        form = UserInfoModelForm()
        return render(request, "user_add.html", {"form":form})
  • 标签

    • 建表时设置了verbose_name字段
    <form method="post">
        {% for field in form %}
        	{{ field.label }} {{ field }}
        {% endfor %}
    </form>
    
  • 表单样式(插件)

    class UserInfoModelForm(forms.ModelForm):
        class Meta:
            model = UserInfo  # 与models建立了依赖关系
            fields = "__all__"
            # 设置Bootstrap样式
            widgets = {
                "name": forms.TextInput(attrs={"class": 'form-control'}),
                "password": forms.PasswordInput(attrs={"class": 'form-control'}),
                "age": forms.NumberInput(attrs={"class": 'form-control'})
            }
    
  • 校验

    def user_add(request):
        if request.method == "GET":
            form = UserInfoModelForm()
            return render(request, "uesr_add.html", {"form": form})
        else:
            # 获取数据
            form = UserInfoModelForm(data=request.POST)
            # 校验数据
            if form.is_valid():
                form.save()
                return redirect("/user/list/")
            else:
                return render(request, "uesr_add.html", {"form": form})
    
  • 中文报错设置

    # settings.py
    LANGUAGE_CODE = "zh-hans"
    
posted @ 2023-04-07 16:14  络辰  阅读(15)  评论(0编辑  收藏  举报