– バリデーションはsaveの時に実行されるので、モデルの更新時にはモデル側でバリデーションをかける
/hello/forms.py
class FriendForm(forms.ModelForm): class Meta: model = Friend fields = ['name','mail','gender','age','birthday']
/hello/models.py
class Friend(models.Model): name = models.CharField(max_length=100) mail = models.EmailField(max_length=200) gender = models.BooleanField() age = models.IntegerField(default=0) birthday = models.DateField()
– save以外に自分でチェックをかけることも可能
/hello/views.py
def check(request): params = { 'title': 'Hello', 'message': 'check validation.', 'form': FriendForm(), } if(request.method == 'POST'): obj = Friend() form = FriendForm(request.POST, instance=obj) params['form'] = form if(form.is_valid()): params['message'] = 'OK!' else: params['message'] = 'no good.' return render(request, 'hello/check.html', params)
/hello/templates/hello/check.html
<body class="container"> <h1 class="display-4 text-primary">{{title}}</h1> <p>{{message|safe}}</p> <form action="{% url 'check' %}" method="post"> {% csrf_token %} <table class="table"> {{ form.as_table }} <tr><th></th><td> <input type="submit" value="click" class="btn btn-primary mt-2"> </td></tr> </table> </form> </body>
– forms.FormとModelFormのバリデーションは異なる
### モデルにバリデーションの組み込み
/hello/models.py
from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Friend(models.Model): name = models.CharField(max_length=100) mail = models.EmailField(max_length=200) gender = models.BooleanField() age = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(150)]) birthday = models.DateField()
### モデルで使えるバリデータ
– MinValueValidator/MaxValueValidator, MinLengthValidator/MaxLengthValidator
from django.db import models from django.core.validators import MinLengthValidator class Friend(models.Model): name = models.CharField(max_length=100, validators=[MinLengthValidator(10)]) mail = models.EmailField(max_length=200, validators=[MinLengthValidator(10)]) gender = models.BooleanField() age = models.IntegerField() birthday = models.DateField()
– EmailValidator/URLValidator
– ProhibitNullCharactersValidator
– RegexValidator
from django.core.validators import RegexValidator class Friend(models.Model): name = models.CharField(max_length=100, validators=[RegexValidator(r'^[a-z]*$')])
バリデーション定義によってmodelに組み込んでいくイメージです。