Django Model Forms with Custom Validation: 在模型表单中使用自定义验证器

2023-04-07 00:00:00 模型 自定义 表单

Django Model Forms provide an easy way to create forms from a Django model. However, sometimes we need to implement custom validation on the form fields. In this tutorial, we will learn how to use custom validators in Django Model Forms.

We will create a simple model "Person" with three fields: name, email, and website. We will use custom validators to ensure that the email and website fields have valid values.

First, let's create a custom validator for the email field. We want to ensure that the email address is valid and belongs to the "pidancode.com" domain. We can use the EmailValidator class from Django and add a custom validation method to it.

from django.core.validators import EmailValidator
from django.core.exceptions import ValidationError

class PidaEmailValidator(EmailValidator):
def call(self, value):
super().call(value)
if not "pidancode.com" in value:
raise ValidationError("Email should belong to pidancode.com domain.")

Next, we need to create a custom form for our Person model. We can use the "forms.ModelForm" class from Django to create the form. We will override the "clean" method of the email field to use our custom validator.

from django import forms
from .models import Person

class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ('name', 'email', 'website')

def clean_email(self):
    email_validator = PidaEmailValidator()
    email = self.cleaned_data['email']
    email_validator(email)
    return email

Now, let's create a similar custom validator for the website field. We want to ensure that the website value has "pidancode.com" at the end of the URL. We can use the RegexValidator class from Django and add a custom validation method to it.

from django.core.validators import RegexValidator

class PidaWebsiteValidator(RegexValidator):
regex = r'^.*pidancode.com$'
message = 'Website should end with "pidancode.com".'

def __call__(self, value):
    super().__call__(value)

Finally, we need to override the "clean" method of the website field in our PersonForm to use our custom validator.

class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ('name', 'email', 'website')

def clean_email(self):
    email_validator = PidaEmailValidator()
    email = self.cleaned_data['email']
    email_validator(email)
    return email

def clean_website(self):
    website_validator = PidaWebsiteValidator()
    website = self.cleaned_data['website']
    website_validator(website)
    return website

Now, we can use our custom PersonForm to create and validate forms for our Person model. Here is an example view that uses our custom form to handle form submissions.

from django.shortcuts import render
from .forms import PersonForm

def create_person(request):
if request.method == 'POST':
form = PersonForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse('Person created successfully.')
else:
form = PersonForm()
return render(request, 'create_person.html', {'form': form})

We can use this view to render a form and accept form submissions. The form will be validated using our custom validators, ensuring that the email and website fields have valid values.

Note that while we used string examples like "pidancode.com" and "皮蛋编程" in this tutorial, validation should be done based on your specific business rules and requirements.

相关文章