我创建了一个联系表单,当处理完成时,它将返回错误div标签中的数据,而不是成功div标签。
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.core.mail import send_mail
from django.contrib import messages
from django.core.mail import send_mail
from .models import Contact
def contact(request):
if request.method == 'POST':
name = request.POST['name']
email = request.POST['email']
subject = request.POST['subject']
message = request.POST['message']
contact = Contact(name=name, email=email, subject=subject, message=message)
contact.save()
# Send email
send_mail(
"From e-learning:"+subject,
message,
'senderemail@gmail.com',
['receiver1@gmail.com', 'receiver2@gmail.com'],
fail_silently=False
)
send_mail(
"Welcome to e-learning",
"Thank very much for contacting us.We received your enquiry. Our team will contact you as early as possible.",
'senderemail@gmail.com',
[email, 'receiver1@gmail.com'],
fail_silently=False
)
messages.success(request, 'Your request has been submitted, a realtor will get back to you soon')
#return redirect('/listings/'+listing_id)
#return redirect('/')
return HttpResponse("Details are submitted")
模板,我已经指出。
<form action="{% url 'contact' %}" method="POST" role="form" class="php-email-form mt-4">
{% csrf_token %}
<div class="form-row">
<div class="col-md-6 form-group">
<input type="text" name="name" class="form-control" id="id_contact_name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="col-md-6 form-group">
<input type="email" class="form-control" name="email" id="id_contact_email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" id="id_content" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validate"></div>
</div>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button type="submit">Send Message</button></div>
</form>
我使用的引导模板(免费版本)。
所有的输出,无论是错误还是成功,都是用类错误消息来代替发送消息。
您的表单是从Ajax提交的。您使用的免费主题将有一个名为Forms的文件夹。删除它,然后像这样更改您的代码
def contact(request):
if request.is_ajax() and request.method == "POST":
contact = Contact()
contact.name = request.POST.get('name')
contact.email = request.POST.get('email')
contact.subject = request.POST.get('subject')
contact.message = request.POST.get('message')
contact.save()
#send email here
return JsonResponse({'massage':"massage"},safe=True)