我想在我的网站上建立一个联系表格。我到处都可以找到PHP电子邮件表单,但是没有Django示例。我不知道自己该怎么做,所以我问是否有人可以从头开始告诉我 - 如何使用Django在网站上发送电子邮件联系表格?
答案 0 :(得分:31)
一个简单的例子可能是:
<强> urls.py 强>
from django.conf.urls import patterns, url
from yourapp import views
urlpatterns = patterns(
'',
url(r'^email/$',
views.email,
name='email'
),
url(r'^thanks/$',
views.thanks,
name='thanks'
),
)
<强> forms.py 强>
from django import forms
class ContactForm(forms.Form):
from_email = forms.EmailField(required=True)
subject = forms.CharField(required=True)
message = forms.CharField(widget=forms.Textarea)
<强> views.py 强>
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from yourapp.forms import ContactForm
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['admin@example.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('thanks')
return render(request, "yourapp/email.html", {'form': form})
def thanks(request):
return HttpResponse('Thank you for your message.')
<强> email.html 强>
<form method="post">
{% csrf_token %}
{{ form }}
<div class="form-actions">
<button type="submit">Send</button>
</div>
</form>
答案 1 :(得分:1)
如果简单很重要,Formspree可能是另一种选择。他们让它变得非常容易。
您只需在代码中插入类似的内容:
<form action="https://formspree.io/your@email.com"
method="POST">
<input type="text" name="name">
<input type="email" name="_replyto">
<textarea name="message"></textarea>
<input type="submit" value="Send">
</form>
然后验证电子邮件,您就可以开始了。
有关详细信息,请this video说明如何执行此操作。
答案 2 :(得分:0)
示例
urlpatterns = patterns(
'',
url(r'^email/$',
views.email,
name='email'
),
url(r'^thanks/$',
views.thanks,
name='thanks'
),
)