我用基本的HTML标签编写了代码,例如,没有问题。邮件已正确发送。但是,当我更改其位置并且HTML标签的邮件功能不起作用时。有什么问题吗?
有效
<h1>Contact Us</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<div class="form-actions">
<button type="submit">Send</button>
</div>
</form>
它不起作用。
<form class="contact-form" action="" method="GET">
{% csrf_token %}
{% for field in form %}
{{ field|add_class:"input" }}
{% endfor %}
<button class="button" type="submit">Send</button>
</form>
views.py
def index(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST or None)
if form.is_valid():
fullname = form.cleaned_data['fullname']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(fullname, message, from_email,
['gulnarnecefova1996@gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('home')
context['form'] = form
return render(request, "index.html", context)
答案 0 :(得分:1)
您所说的not working
表格:
<form class="contact-form" action="" method="GET">
{% csrf_token %}
{% for field in form %}
{{ field|add_class:"input" }}
{% endfor %}
<button class="button" type="submit">Send</button>
</form>
您可以看到您已经使用过method="GET"
。然后在您的意见中:
def index(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST or None)
if form.is_valid():
fullname = form.cleaned_data['fullname']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(fullname, message, from_email,
['gulnarnecefova1996@gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('home')
context['form'] = form
return render(request, "index.html", context)
在这里,您已使用以下代码在POST method block
内部发送邮件:
else:
form = ContactForm(request.POST or None)
if form.is_valid():
fullname = form.cleaned_data['fullname']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(fullname, message, from_email,
['gulnarnecefova1996@gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('home')
因此,在您提交表单时,它是作为get
请求发送的。 get
请求正在由以下代码块处理:
if request.method == 'GET':
form = ContactForm()
因此,邮件功能不起作用。
尝试以html形式将方法更改为post
。