欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Django forms组件的使用教程

程序员文章站 2022-03-20 15:12:32
编写django的form表单,非常类似我们在模型系统里编写一个模型。在模型中,一个字段代表数据表的一列,而form表单中的一个字段代表
中的一个&l...

编写django的form表单,非常类似我们在模型系统里编写一个模型。在模型中,一个字段代表数据表的一列,而form表单中的一个字段代表<form>中的一个<input>元素。

一,forms组件:

校验字段功能

针对一个实例:注册用户讲解。

模型:models.py

class userinfo(models.model):
  name=models.charfield(max_length=32)
  pwd=models.charfield(max_length=32)
  email=models.emailfield()
  tel=models.charfield(max_length=32)

模板: register.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>title</title>

</head>
<body>

<form action="" method="post">
  {% csrf_token %} 
  <div>
    <label for="user">用户名</label>
    <p><input type="text" name="name" id="name"></p>
  </div>
  <div>
    <label for="pwd">密码</label>
    <p><input type="password" name="pwd" id="pwd"></p>
  </div>
  <div>
    <label for="r_pwd">确认密码</label>
    <p><input type="password" name="r_pwd" id="r_pwd"></p>
  </div>
   <div>
    <label for="email">邮箱</label>
    <p><input type="text" name="email" id="email"></p>
  </div>
  <input type="submit">
</form>

</body>
</html>

视图函数:register

# forms组件
from django.forms import widgets

wid_01=widgets.textinput(attrs={"class":"form-control"})
wid_02=widgets.passwordinput(attrs={"class":"form-control"})

class userform(forms.form):
  name=forms.charfield(max_length=32,
             widget=wid_01
             )
  pwd=forms.charfield(max_length=32,widget=wid_02)
  r_pwd=forms.charfield(max_length=32,widget=wid_02)
  email=forms.emailfield(widget=wid_01)
  tel=forms.charfield(max_length=32,widget=wid_01)

def register(request):

  if request.method=="post":
    form=userform(request.post)
    if form.is_valid():
      print(form.cleaned_data)    # 所有干净的字段以及对应的值
    else:
      print(form.cleaned_data)    #
      print(form.errors)       # errordict : {"校验错误的字段":["错误信息",]}
      print(form.errors.get("name")) # errorlist ["错误信息",]
    return httpresponse("ok")
  form=userform()
  return render(request,"register.html",locals())

1,渲染标签功能

渲染方式1

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>title</title>
  <!-- 最新版本的 bootstrap 核心 css 文件 -->
  <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" integrity="sha384-bvyiisifek1dgmjrakycuhahrg32omucww7on3rydg4va+pmstsz/k68vbdejh4u" crossorigin="anonymous">
</head>
<body>
<h3>注册页面</h3>
<div class="container">
  <div class="row">
    <div class="col-md-6 col-lg-offset-3">

        <form action="" method="post">
          {% csrf_token %}
          <div>
            <label for="">用户名</label>
            {{ form.name }}
          </div>
          <div>
            <label for="">密码</label>
            {{ form.pwd }}
          </div>
          <div>
            <label for="">确认密码</label>
            {{ form.r_pwd }}
          </div>
          <div>
            <label for=""> 邮箱</label>
            {{ form.email }}
          </div>

          <input type="submit" class="btn btn-default pull-right">
        </form>
    </div>
  </div>
</div>
</body>
</html>

渲染方式2

<form action="" method="post">
          {% csrf_token %}

          {% for field in form %}
            <div>
              <label for="">{{ field.label }}</label>
              {{ field }}
            </div>
          {% endfor %}
          <input type="submit" class="btn btn-default pull-right">

</form>

渲染方式3

<form action="" method="post">
  {% csrf_token %}

  {{ form.as_p }}
  <input type="submit" class="btn btn-default pull-right">

</form>

2,显示错误与重置输入信息功能

视图

def register(request):

  if request.method=="post":
    form=userform(request.post)
    if form.is_valid():
      print(form.cleaned_data)    # 所有干净的字段以及对应的值
    else:
      print(form.cleaned_data)    #
      print(form.errors)       # errordict : {"校验错误的字段":["错误信息",]}
      print(form.errors.get("name")) # errorlist ["错误信息",]
    return render(request,"register.html",locals())
  form=userform()
  return render(request,"register.html",locals())

模板

<form action="" method="post" novalidate>
  {% csrf_token %}

  {% for field in form %}
    <div>
      <label for="">{{ field.label }}</label>
      {{ field }} <span class="pull-right" style="color: red">{{ field.errors.0 }}</span>
    </div>
  {% endfor %}
  <input type="submit" class="btn btn-default">

</form>

3,局部钩子与全局钩子

模板

# forms组件
from django.forms import widgets

wid_01=widgets.textinput(attrs={"class":"form-control"})
wid_02=widgets.passwordinput(attrs={"class":"form-control"})

from django.core.exceptions import validationerror
class userform(forms.form):
  name=forms.charfield(max_length=32,
             widget=wid_01
             )
  pwd=forms.charfield(max_length=32,widget=wid_02)
  r_pwd=forms.charfield(max_length=32,widget=wid_02)
  email=forms.emailfield(widget=wid_01)
  tel=forms.charfield(max_length=32,widget=wid_01)

  # 局部钩子
  def clean_name(self):
    val=self.cleaned_data.get("name")
    if not val.isdigit():
      return val
    else:
      raise validationerror("用户名不能是纯数字!")

  # 全局钩子

  def clean(self):
    pwd=self.cleaned_data.get("pwd")
    r_pwd=self.cleaned_data.get("r_pwd")

    if pwd==r_pwd:
      return self.cleaned_data
    else:
      raise validationerror('两次密码不一致!')

def register(request):

  if request.method=="post":
    form=userform(request.post)
    if form.is_valid():
      print(form.cleaned_data)    # 所有干净的字段以及对应的值
    else:
      clean_error=form.errors.get("__all__")

    return render(request,"register.html",locals())
  form=userform()
  return render(request,"register.html",locals())

视图

<form action="" method="post" novalidate>
      {% csrf_token %}

      {% for field in form %}
        <div>
          <label for="">{{ field.label }}</label>
          {{ field }}
          <span class="pull-right" style="color: red">
             {% if field.label == 'r pwd' %}
             <span>{{ clean_error.0 }}</span>
             {% endif %}
             {{ field.errors.0 }}
          </span>
        </div>
      {% endfor %}
      <input type="submit" class="btn btn-default">

</form>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。