在这里,我有一个表,并且有一个复选框,我想向该表的所有已检查数据发送电子邮件。为此,我尝试了以下方法。但这是行不通的。问题是在返回检查项目列表时。被检查的项目不退还。如何解决?
模板
<tbody>
{% for contact in contacts %}
<tr>
<td>
<input name ="messages" type="checkbox"
id="contact-{{contact.id}}" value={{contact.id}}">
<label for="contact-{{contact.id}}">{{ forloop.counter }}</label>
</td>
<td>{{ contact.name }}</td>
<td>{{ contact.email }}</td>
<td>{{ contact.subject }}</td>
<td>{{ contact.message }}</td>
</tr>
{% endfor %}
</tbody>
//modal
<button class="btn btn-primary send-mail-to-selected-btn" type="button"
data-toggle="modal" data-target="#item-unit-modal1">
Send Mail To Selected Email
</button>
<div class="modal" id="item-unit-modal1">
<div class="modal-body">
<form method="POST" action="{% url 'admin:send_mail_selected_contact' %}" class="unit-ajax-form">
{% csrf_token %}
<p><label>Subject</label> <input type="text" name="subject" class="form-control required" placeholder="Enter subject" ></p>
<p><label>Message</label> <textarea name="message" class="form-control required" placeholder="Enter message" ></textarea></p>
<button class="btn btn-primary mt-30">Send Mail</button>
</form>
</div>
views.py
def send_mail_selected_contact(request):
selected_contact = ContactForm.objects.filter(id__in=request.POST.getlist('messages'))
print(selected_contact)
form = SendMailContact(request.POST or None)
if form.is_valid():
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
for contact in selected_contact:
send_mail(subject, message, ' <settings.EMAIL_HOST_USER>', [contact.email])
messages.success(request, 'Mail Sent')
return redirect('admin:contact_message')
ajax
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).on('click', '.send-mail-to-selected-btn', function(){
var messages = new Array();
$("input:checked").each(function() {
messages.push($(this).val());
});
console.log(messages); #here i can see the id of checked email
});
$.ajax({
url:'admin/selected/send/mail/contact/',
data:{
name: name,
messages: messages,
}
});
</script>
forms.py
class SendMailContact(forms.Form):
subject = forms.CharField(max_length=250)
message = forms.CharField(widget=forms.Textarea)
答案 0 :(得分:3)
您需要将ajax
调用移到点击处理程序中。
此外,由于您正在监听点击事件而不是提交事件,因此无法阻止浏览器也提交该表单。有关侦听提交,取消浏览器默认行为并在提交时进行AJAX调用的更新实现,请参见下文。
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).on('submit', '.send-mail-to-selected-btn', function(ev){
ev.preventDefault()
var messages = new Array();
$("input:checked").each(function() {
messages.push($(this).val());
});
console.log(messages); #here i can see the id of checked email
$.ajax({
url:'admin/selected/send/mail/contact/',
data:{
name: name,
messages: messages,
}
});
});
</script>