Django formsコンポーネントの使用教程


Djangoの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.

<!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>
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。