如何使用django-contact-form(第三方应用程序)?

5
django-contact-form 是一个流行的第三方应用程序,旨在为基于 Django 的站点提供简单、可扩展的联系表单功能,以消除繁琐和重复。然而,我发现文档有些难以理解(也许是我不够聪明)。

经过一番搜索和测试,最终我让它正常工作了。我将写下步骤和代码,希望能帮助那些未来可能使用它的人。


我投票关闭此问题,因为虽然这很有用,但这并不是一个问题。您能否以某种方式重新措辞问题和答案,以遵循 Stack Exchange 格式? - user764357
@LegoStormtroopr 你的意思是我应该删除最后一段吗? - laike9m
1个回答

19

1. 安装

pip install django-contact-form

2. 将必要的配置添加到 settings.py 文件中

EMAIL_USE_TLS = True  
EMAIL_HOST = 'smtp.gmail.com'  
EMAIL_PORT = 587  
EMAIL_HOST_USER = 'laike9m@gmail.com'  # this is my email address, use yours
EMAIL_HOST_PASSWORD = os.environ['EMAIL_HOST_PASSWORD']   # set environ yourself

ADMINS = (
    ('your_name', 'your_email'),   # email will be sent to your_email
)

MANAGERS = ADMINS

此外,在你的INSTALLED_APPS中添加'contact_form'

3. 创建联系表单模板

在你的templates文件夹中创建一个名为contact_form的文件夹,并将以下文件添加到其中:

templates  
    └─contact_form  
          contact_form.html  
          contact_form.txt  
          contact_form_sent.html  
          contact_form_subject.txt  

您可以编写自己的内容,以下是我使用的内容:

contact_form.html

{% extends 'laike9m_blog/blog_base.html' %}

{% block content %}
  <h2>Contact Form</h2>
  <p>To send us a message fill out the below form.</p>
  <form method="post">{% csrf_token %}
    <p>Name: <input type="text" name="name"></p>
    <p>Your e-mail: <input type="text" name="email"></p>
    <p>Message: <textarea name="body" rows="10" cols="50"></textarea></p>
    <input type="submit" value="Submit">
  </form>
{% endblock content %}

联系表单.txt

{{ name }}
{{ email }}
{{ body }} 

联系表单已发送.html

{% extends 'laike9m_blog/blog_base.html' %}

{% block content %}
  <h2>Your message was sent.</h2>
{% endblock content %}

联系表单主题.txt

message from {{ name }}

4. URLconf

将这一行添加到您的URLconf中:

(r'^contact/', include('contact_form.urls')),

全部完成


1
如果我想在主页上放置我的联系表格呢?(在页面底部!) - Mazdak
@Kasra Eh,我不知道,抱歉。也许你可以向创建者寻求帮助。 - laike9m
@Kasra 要将表单嵌入到主页面中,请参考以下教程:atsoftware.de/2015/02/…。基本上,您的主视图应该是ContactFormView的子类,并添加示例CustomContactFormView方法,以便您仍然可以管理原始的主页面以及添加的联系表单功能。按原样添加在教程中提供的form.py模块。然后,所有联系表单的HTML文档都应该扩展您的主页面HTML,以便保留原始内容并添加联系表单功能。 - ecoe
@ecoe 谢谢你的建议!现在我离开了 jdngo,稍后会尝试这个,谢谢! - Mazdak
1
请将您的回复添加到文档中。谢谢。 - edepe
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接