Django Forms.py电子邮件和电话验证 [英] Django Forms.py Email And Phone Validation
问题描述
我有一个使用forms.py创建的联系表单,我想使用正则表达式或任何内置的Django验证器为电子邮件和电话字段添加验证。我使用的唯一文件是forms.py,views.py和html模板(此联系表单没有models.py)。如果用户输入了错误的电话号码或电子邮件,我想向他们显示一条消息,指出其格式不正确,并且他们需要更正其输入。在用户输入有效数据之前,不能提交表单。
I have a contact form created with forms.py that I would like to add validation with regular expressions or any built in Django validators for the email and phone fields. The only files I am using are forms.py, views.py, and the html template (there is no models.py for this contact form). If the user enters an incorrect phone number or email, I want to show them a message saying their format is incorrect and that they need to correct their input. The form should not be able to be submitted until the user enters valid data.
现在在表单中输入虚假数据,然后提交它会导致表单不执行任何操作(它转到网址中的#),但用户不知道电子邮件是否发送。
Right now entering fake data into the form and then submitting it causes the form to not do anything (it goes to # in the url) but the user has no idea if the email sent or not.
我在下面尝试过的内容:
What I have tried below:
from django import forms
from django.core.validators import EmailValidator
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
class ContactForm(forms.Form):
contact_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'autocomplete':'off'}), required=True)
contact_email = forms.EmailField(error_messages={'invalid': 'This is my email error msg.'}, widget=forms.TextInput(attrs={'class':'form-control', 'autocomplete':'off'}), required=True)
contact_subject = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'autocomplete':'off'}), required=True)
contact_phone = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'autocomplete':'off'}), required=True)
content = forms.CharField(
required=True,
widget=forms.Textarea(attrs={'class':'form-control', 'autocomplete':'off'})
)
# the new bit we're adding
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['contact_name'].label = "Full Name:"
self.fields['contact_email'].label = "Email:"
self.fields['contact_subject'].label = "Subject:"
self.fields['contact_phone'].label = "Phone:"
self.fields['content'].label = "Message:"
def clean_email(self):
email = self.cleaned_data['contact_email']
validator = RegexValidator("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
validator(email)
return email
视图。 py:
Views.py:
def contact(request):
form_class = ContactForm
# new logic!
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
recaptcha_response = request.POST.get('g-recaptcha-response')
url = 'https://www.google.com/recaptcha/api/siteverify'
payload = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
data = urllib.parse.urlencode(payload).encode()
req = urllib.request.Request(url, data=data)
response = urllib.request.urlopen(req)
result = json.loads(response.read().decode())
print('result:' + str(result))
print('recaptcha_response:' + str(recaptcha_response))
print('result_success:' + str(result['success']))
if (not result['success']) or (not result['action'] == 'contact'):
messages.error(request, 'Invalid reCAPTCHA. Please try again.')
contact_name = request.POST.get(
'contact_name'
, '')
contact_subject = request.POST.get(
'contact_subject'
, '')
contact_email = request.POST.get(
'contact_email'
, '')
contact_phone = request.POST.get(
'contact_phone'
, '')
form_content = request.POST.get('content', '')
# Email the profile with the
# contact information
template = get_template('contact_template.txt')
context = {
'contact_name': contact_name,
'contact_email': contact_email,
'contact_subject': contact_subject,
'contact_phone': contact_phone,
'form_content': form_content,
}
content = template.render(context)
email = EmailMessage(
contact_subject,
content,
"Your website" +'',
['email@gmail.com'],
headers = {'Reply-To': contact_email }
)
email.send()
messages.info(request, "Your message was sent successfully. Thank you for reaching out.")
return render(request, 'contact.html', {
'form': form_class,
})
HTML模板:
Html template:
<form id='cform' action="#" method="post">
{% csrf_token %}
{{ form.as_p }}
<script src='https://www.google.com/recaptcha/api.js?render=<KEY>'></script>
<div class="g-recaptcha" data-sitekey="<KEY>"></div>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('<KEY>', {action: 'contact'})
.then(function(token) {
ginput = document.createElement('input');
ginput.type = "hidden";
ginput.name = "g-recaptcha-response";
ginput.value = token;
document.getElementById("cform").appendChild(ginput);
});
});
</script>
<button type="submit" class="btn btn-primary form-control">Submit</button>
</form>
我该如何仅使用Django而不使用JavaScript?
How would I do this using Django only and without JavaScript?
推荐答案
您可以使用 EmailValidator
代替 RegexValidator
。这样,您无需编写可以可靠地测试电子邮件地址的正则表达式(很难弄清楚)。
You can use EmailValidator
instead of RegexValidator
. That way you don't need to write a regex that can reliably test email addresses (which is hard to get right).
并验证我将使用的电话号码电话号码库。 https://github.com/daviddrysdale/python-phonenumbers
And to validate a phone number I would use the phonenumbers library. https://github.com/daviddrysdale/python-phonenumbers
更新
Djano表单文档非常好。答案在这里 https://docs.djangoproject.com/en/3.0/ref / forms /
The Djano forms documentation is very good. The answers are here https://docs.djangoproject.com/en/3.0/ref/forms/
我给您一些指针。
表单处理示例具有基于类的视图的联系表。
The example for form handling with class-based views is a contact form.
https://docs.djangoproject.com/en/3.0/topics/class-based-views/generic-editing/
此参考非常出色:
https://ccbv.co.uk/projects/Django/2.2/django.views.generic.edit/FormView/
对于电子邮件字段,您要执行的所有操作均由defualt处理。这就足够了:
For the email field everything you are trying to do is handled by defualt. This is enough:
class ContactForm(forms.Form):
contact_email = forms.EmailField()
对于电话号码,您可以编写自己的验证器,引用 https://docs.djangoproject.com/en/3.0/ref/forms/validation/ 和电话号码文档。
For the phone number, you can write your own validator, referring to https://docs.djangoproject.com/en/3.0/ref/forms/validation/ and the phonenumbers documentation. Something like:
from django.core.exceptions import ValidationError
import phonenumbers
def validate_phone_number(value):
z = phonenumbers.parse(value, None)
if not phonenumbers.is_valid_number(z):
raise ValidationError(
_('%(value) is not a valid phone number'),
params={'value': value},
)
然后
contact_phone = models.CharField(validators=[validate_phone_number])
这篇关于Django Forms.py电子邮件和电话验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!