10.3. Forms Clean
10.3.1. Use Case - 1
File: myproject/shop/forms.py
:
.. code-block:: python
from django import forms
- class ContactUsForm(forms.Form):
sender = forms.EmailField() subject = forms.CharField() body = forms.CharField(widget=forms.Textarea)
10.3.2. Use Case - 2
File: myproject/shop/forms.py
:
import re
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from shop.models import Customer
class ContactCreateForm(forms.ModelForm):
class Meta:
model = Customer
fields = ['firstname', 'lastname']
def regex(self, pattern, text):
if not re.match(pattern, text):
raise ValidationError(_(f'Invalid character'))
def clean_firstname(self):
firstname = self.cleaned_data['firstname']
firstname = firstname.title()
self.regex(pattern=r'^[A-Z][a-z]{1,20}$', text=firstname)
return firstname
def clean_lastname(self):
lastname = self.cleaned_data['lastname']
lastname = lastname.title()
self.regex(pattern=r'^[A-Z][a-z]{1,20}$', text=lastname)
return lastname