Django中的联系表单
我有一个联系表单,运行得很好,没有任何错误。唯一让我不明白的是,当我点击发送按钮时,没有收到任何消息。有人能告诉我为什么或者哪里出问题了吗?我只有一个页面叫做联系,没有感谢页面!谢谢。
这是我的代码:
models.py
class Subject(models.Model):
question_ = 0
question_one = 1
question_two = 2
question__three = 3
STATUS_CHOICES = (
(question_, ''),
(question_one, 'I have a question'),
(question_two, 'Help/Support'),
(question__three, 'Please give me a call'),
)
class Contact(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=150)
subject = models.CharField(choices=Subject.STATUS_CHOICES, default=1, max_length=100)
phone_number = models.IntegerField()
message = models.TextField()
def save(self, *args, **kwargs):
super(Contact, self).save(*args, **kwargs)
return 'Contact.save'
forms.py
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
import floppyforms as forms
from django_enumfield import enum
class SubjectEnum(enum.Enum):
question_ =0
question_one = 1
question_two = 2
question__three = 3
STATUS_CHOICES = (
(question_, ''),
(question_one, 'I have a question'),
(question_two, 'Help/Support'),
(question__three, 'Please give me a call'),
)
class ContactForm(forms.Form):
name = forms.CharField(required=True)
email = forms.EmailField(required=True)
subject = forms.TypedChoiceField(choices=SubjectEnum.STATUS_CHOICES, coerce=str)
phone_number = forms.IntegerField(required=False)
message = forms.CharField(widget=forms.Textarea)
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'Submit'))
super(ContactForm, self).__init__(*args, **kwargs)
views.py
from django.conf import settings
from django.core.mail import send_mail
from django.views.generic import FormView
from .forms import ContactForm
class ContactFormView(FormView):
form_class = ContactForm
template_name = "contact/email_form.jade"
success_url = '/email-sent/'
def form_valid(self, form):
message = "{name} / {email} said: ".format(
name=form.cleaned_data.get('name'),
email=form.cleaned_data.get('email'))
message += "\n\n{0}".format(form.cleaned_data.get('message'))
send_mail(
subject=form.cleaned_data.get('subject').strip(),
message=message,
from_email="info@example.com",
recipient_list=[settings.LIST_OF_EMAIL_RECIPIENTS],
)
return super(ContactFormView, self).form_valid(form)
2 个回答
0
这部分可能有问题:
recipient_list=[settings.LIST_OF_EMAIL_RECIPIENTS],
如果 settings.LIST_OF_EMAIL_RECIPIENTS
已经是一个列表了,那么你就把它放在了另一个列表里面。
总的来说,当你遇到代码不工作的情况时,建议你用调试工具逐步检查代码,或者加一些打印语句,看看代码运行时发生了什么。这样会让你更容易找到问题所在。
1
其实有个更简单、更好的方法来做到这一点。
class Subject(models.Model):
question_ = 0
question_one = 1
question_two = 2
question__three = 3
STATUS_CHOICES = (
(question_, ''),
(question_one, 'I have a question'),
(question_two, 'Help/Support'),
(question__three, 'Please give me a call'),
)
你不需要新建一个类,只需要这样做。在你看到的0、1、2、3这些数字是用来识别每个选择的。你可以在第一部分放任何东西,比如0、1、2、3,或者用"IHAQ"来表示"I have a question"(我有一个问题)。
STATUS_CHOICES = (
("0", ""),
("1", "I have a question"),
("2", "Help/Support"),
("3", "Please give me a call"),
)