2015-02-09 15 views
9

Tôi muốn tạo biểu mẫu liên hệ trên trang web của mình. Tôi có thể tìm thấy các hình thức e-mail PHP ở khắp mọi nơi, nhưng không có ví dụ Django. Tôi không có ý tưởng làm thế nào để làm điều đó bản thân mình, vì vậy tôi hỏi nếu có bất cứ ai có thể cho tôi biết từ đầu - làm thế nào để làm cho một hình thức liên lạc e-mail trên trang web bằng cách sử dụng Django?Ví dụ về mẫu e-mail Python Django

+0

Bạn có thể sử dụng mã trong github này: [https://github.com/jezdez/django-contact-form](https://github.com/jezdez/django-contact-form) hoặc The a xem [ở đây] (http://www.pydanny.com/simple-django-email-form-using-cbv.html) để biết ví dụ đơn giản. –

Trả lời

29

Một ví dụ đơn giản có thể là:

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

Cảm ơn, đó là những thứ khá thú vị ở đây! – Nhor

1

Nếu đơn giản là quan trọng, Formspree có thể là một sự thay thế. Họ làm cho nó siêu dễ dàng.

Bạn chỉ cần chèn một cái gì đó như thế này trong mã của bạn:

<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> 

Sau đó, bạn xác nhận các e-mail, và bạn đã sẵn sàng để đi.

Để biết thêm thông tin, this video giải thích cách thực hiện.