为什么RegexValidator没有显示消息?看起来我发布了太多代码...... 这是我的views.py:
from polls.forms import ContactForm
from django.template.loader import get_template
from django.core.mail import EmailMessage
from django.template import Context, Template, RequestContext
from django.shortcuts import render
from django.shortcuts import redirect
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.template.loader import render_to_string, get_template
def index(request):
return HttpResponse("Hello, world. You're at the poll index.")
def contact(request):
form_class = ContactForm
# new logic!
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
contact_name = request.POST.get('contact_name', '')
contact_email = request.POST.get('contact_email', '')
phone_number = request.POST.get('phone_number', '')
content = request.POST.get('content', '')
# Email the profile with the
# contact information
message = render_to_string('contact_template.txt', {'contact_name': contact_name, 'contact_email': contact_email, 'phone_number': phone_number, 'form_content': content}, context_instance=RequestContext(request))
email = EmailMessage("New contact form submission", message, "annadrybulska@gmail.com" +'', ['annadrybulska@gmail.com'], headers = {'Reply-To': contact_email })
email.send()
return redirect('contact')
return render(request, 'contact.html', {'form': form_class,})
这是我的forms.py(其中RegexValidator给我带来了麻烦!):
from django import forms
from django.core.validators import RegexValidator
from django.core import validators
from django.core.exceptions import ValidationError
#new form
class ContactForm(forms.Form):
contact_name = forms.CharField(required=True)
contact_email = forms.EmailField(required=True)
phone_number = forms.CharField(required=True, max_length=9, validators=[RegexValidator(regex=r'^\d+$', message='Nieprawidłowy numer telefonu.', code='invalid_number', inverse_match=None, flags=0
)])
content = forms.CharField(required=True, widget=forms.Textarea)
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['contact_name'].label = "Imię:"
self.fields['contact_email'].label = "E-mail:"
self.fields['phone_number'].label = "Numer telefonu:"
self.fields['content'].label = "Wiadomość:"
和我的template.py:
{% block content %}
<h1>Formularz kontaktowy</h1>
<form role="form" action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Wyślij</button>
</form>
{% endblock %}
答案 0 :(得分:2)
如果您的帖子请求为form_class
且表单无效,则您将转入模板上下文form
而不是POST
。要解决此问题,请将最后一行视图更改为以下三行:
else:
form = form_class()
return render(request, 'contact.html', {'form': form,})
如果没有帖子数据,则会创建空表单并将form
而不是form_class
传递给您的模板。