我有一个使用forms.py创建的联系表单,我想为电子邮件和电话字段添加正则表达式或任何内置Django验证器进行验证。 我仅使用的文件是forms.py、views.py和HTML模板(此联系表单没有models.py)。 如果用户输入不正确的电话号码或电子邮件,则希望向他们显示一条消息,说明其格式不正确,并且需要更正其输入。在用户输入有效数据之前,表单不应该能够被提交。
目前,在表单中输入虚假数据并提交后,表单不会执行任何操作(跳转到url中的#),但用户不知道邮件是否发送成功。
我尝试过以下内容:
我该如何仅使用Django而不使用JavaScript来实现这一点?
目前,在表单中输入虚假数据并提交后,表单不会执行任何操作(跳转到url中的#),但用户不知道邮件是否发送成功。
我尝试过以下内容:
Forms.py:
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
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模板:
<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来实现这一点?