from django import forms
from django.core.exceptions import ValidationError
class ContactForm(forms.Form):
name = forms.CharField()
email = forms.EmailField()
def clean(self):
cleaned_data = super().clean()
name = cleaned_data.get('name')
email = cleaned_data.get('email')
if name and email:
if 'example.com' in email:
raise ValidationError("Email addresses from example.com are not allowed.")
from django import forms
class ContactForm(forms.Form):
name = forms.CharField()
email = forms.EmailField()
def clean_email(self):
email = self.cleaned_data.get('email')
if email and 'example.com' in email:
self.add_error('email', "Email addresses from example.com are not allowed.")
return email
from django.shortcuts import render
from .forms import ContactForm
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# 处理表单数据
pass
else:
# 手动报告表单验证错误
form.errors['email'] = ["Email addresses from example.com are not allowed."]
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})