### バリデータ作成
– reがpythonの正規表現モジュール
/hello/models.py
import re from django.db import models from django.core.validators import ValidationError def number_only(value): if(re.match(r'^[0-9]*$', value) == None): raise ValidationError( '%(value)s is not Number!', params={'value': value}, ) class Friend(models.Model): name = models.CharField(max_length=100, validators=[number_only]) mail = models.EmailField(max_length=200) gender = models.BooleanField() age = models.IntegerField() birthday = models.DateField()
### エラーメッセージ作成
– フォーム全体のエラーメッセージを取り出すにはform.errorsを使う
– フォームの項目からエラーを取り出すことができる
/hello/templates/hello/check.html
<body class="container"> <h1 class="display-4 text-primary">{{title}}</h1> <p>{{message|safe}}</p> <ol class="list-group"> {% for item in form %} <li class="list-group-item py-2">{{ item.name }}{{ item.value }}:{{ item.errors.as_text }}</li> {% endfor %} </ol> <table class="table mt-4"> <form action="{% url 'check' %}" method="post"> {% csrf_token %} <tr> <th>名前</th> <td>{{ form.name }}</td> </tr> <tr> <th>メール</th> <td>{{ form.mail }}</td> </tr> <tr> <th>性別</th> <td>{{ form.gender }}</td> </tr> <tr> <th>年齢</th> <td>{{ form.age }}</td> </tr> <tr> <th>誕生日</th> <td>{{ form.birthday }}</td> </tr> <tr><th></th><td> <input type="submit" value="click" class="btn btn-primary"> </td></tr> </form> </table> </body>
### ModelFormのカスタマイズ
/hello/forms.py
class FriendForm(forms.ModelForm): class Meta: model = Friend fields = ['name','mail','gender','age','birthday'] widgets = { 'name': forms.TextInput(attrs={'class':'form-control'}), 'mail': forms.EmailInput(attrs={'class':'form-control'}), 'age': forms.NumberInput(attrs={'class':'form-control'}), 'birthday': forms.DateInput(attrs={'class':'form-control'}), }
/hello/templates/hello/check.html
<body class="container"> <h1 class="display-4 text-primary">{{title}}</h1> <p>{{message|safe}}</p> <ol class="list-group mb-4"> {% for item in form %} <li class="list-group-item py-2">{{ item.name }}{{ item.value }}:{{ item.errors.as_text }}</li> {% endfor %} </ol> <form action="{% url 'check' %}" method="post"> {% csrf_token %} <div class="form-group">名前{{ form.name }}</div> <div class="form-group">メール{{ form.mail }}</div> <div class="form-group">性別{{ form.gender }}</div> <div class="form-group">年齢{{ form.age }}</div> <div class="form-group">誕生日{{ form.birthday }}</div> <div class="form-group"> <input type="submit" value="click" class="btn btn-primary"> </div> </body>