2015-02-09 57 views
9

我想在我的網站上創建聯繫表單。我可以在任何地方找到PHP電子郵件表單,但是沒有Django的例子。我不知道如何自己做,所以我問是否有人可以從頭開始告訴我 - 如何使用Django在網站上製作電子郵件聯繫表單?Python Django電子郵件表單示例

+0

你可以使用這個github中的代碼: [https://github.com/jezdez/django-contact-form](https://github.com/jezdez/django-contact-form)或者a看看[這裏](http://www.pydanny.com/simple-django-email-form-using-cbv.html)爲一個簡單的例子。 – 2015-02-09 00:15:33

回答

29

一個簡單的例子可以是:

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, ['[email protected]']) 
      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> 
+3

謝謝,這裏非常酷的東西! – Nhor 2015-02-10 00:00:47

1

如果簡單是很重要的,Formspree可能是一個選擇。他們使它變得非常簡單。

你只需要插入這樣的事情在你的代碼:

<form action="https://formspree.io/[email protected]" 
     method="POST"> 
    <input type="text" name="name"> 
    <input type="email" name="_replyto"> 
    <textarea name="message"></textarea> 
    <input type="submit" value="Send"> 
</form> 

然後你驗證電子郵件,你準備好去。

欲瞭解更多信息,this video解釋如何做到這一點。