对于上述问题,我使用的是表格,只要有点击电子邮件发送给用户
models.py
from django import forms
class Notification(forms.Form):
email = forms.EmailField()
message = forms.CharField()
这是views.py
from django.shortcuts import render
from django.conf import settings
from django.core.mail import send_mail
from .models import Notification
def notification(request):
form = Notification(request.POST or None)
if form.is_valid():
message = form.cleaned_data["message"]
email = form.cleaned_data["email"]
subject = 'Order Status at Table'
from_email = settings.EMAIL_HOST_USER
to_email = [email,]
contact_message = "%s"%(
message)
send_mail(subject,
contact_message,
from_email,
to_email,
fail_silently=True)
context = {
"email": email,
"message": message
}
return render(request, "send.html", context)
send.html
<form name="notification" method='POST' action= "">{% csrf_token %}
<select name="message">
<option value="5 min">5 min</option>
<option value="10 min">10 min</option>
<option value="15 min">15 min</option>
<option value="20 min">20 min</option>
</select>
<select name="email">
<option value="example@example.com">example@example.com</option>
</select>
<br><br>
<input type="submit">
</form>
点击提交按钮后,我被重定向到空白屏幕(并且不会发送电子邮件)
在控制台中,我可以看到消息和用户电子邮件通过,但未发送电子邮件
在我的设置中,我已配置邮件及其工作
答案 0 :(得分:2)
notification
视图中有很多事情发生。
您正在导入模型Notification
而不是表单1。这就是您应该为此表单命名的一个原因NotificationForm
。
您正在创建context
,但如果请求是GET
,则此上下文将包含未定义的变量。
你正在硬编码表格,这不是Django的方式。您应该在表单中创建选项。
所以,请转到这些:
# forms.py
from django import forms
class NotificationForm(forms.Form):
EMAIL_CHOICES = (
('example@example.com', 'example@example.com'),
)
MESSAGE_CHOICES = (
('5 min', '5 min'),
('10 min', '10 min'),
('15 min', '15 min'),
('20 min', '20 min'),
)
email = forms.EmailField(widget=forms.Select(choices=EMAIL_CHOICES))
message = forms.CharField(widget=forms.Select(choices=MESSAGE_CHOICES))
然后在您的views.py
文件中:
# views.py
from .forms import NotificationForm
def notification(request):
email = ''
message = ''
form = NotificationForm()
if request.method == 'POST':
form = NotificationForm(request.POST)
if form.is_valid():
message = form.cleaned_data['message']
email = form.cleaned_data['email']
subject = 'Order Status at Table'
from_email = settings.EMAIL_HOST_USER
to_email = [email,]
contact_message = '{}'.format(message)
send_mail(subject, contact_message, from_email, to_email, fail_silently=True)
context = {
'form': form,
'email': email,
'message': message
}
return render(request, "send.html", context)
最后在send.html
写下这些:
<form name="notification" method='post' action="">{% csrf_token %}
{{ form }}
<br><br>
<input type="submit">
</form>