【问题标题】:Django Contact FormDjango 联系表
【发布时间】:2019-06-27 13:32:31
【问题描述】:

我使用 django 创建了一个联系表单,用于发送姓名、电子邮件和消息。表单通过名称成功通过,主题附加但是只有部分消息到达 gmail 而不是整个消息。我怎样才能获得完整的消息以显示在 gmail 帐户上?

from django.db import models

# Create your models here.
class Contact(models.Model):

    name = models.CharField(max_length=30)
    email = models.EmailField()
    message = models.TextField()


    def __str__(self):
        return self.name

表格

from django import forms
from django.forms import ModelForm
from .models import Contact

class ContactForm(forms.ModelForm):

    class Meta:
        model = Contact
        fields = ('name', 'email', 'message',)

观看次数

def contact(request):
mapbox_access_token = 'pk.my_mapbox_access_token'
if request.method == 'GET':
    form = ContactForm()
else:
    form = ContactForm(request.POST)
    if form.is_valid():
        sender_name = form.cleaned_data['name']
        emailFrom = form.cleaned_data['email']
        message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message'])


        form.save()
        try:
            send_mail('New Enquiry', message, emailFrom, ['va.glazing@gmail.com'],fail_silently=False, )
        except BadHeaderError:
            return HttpResponse('Invalid header found')
        return redirect('success')

return render(request, "contact.html",{'form': form})
#settings

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '****.***.com'
EMAIL_HOST_PASSWORD = '******'
EMAIL_PORT = 587
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

这是电子邮件通过后我得到的结果图像。

https://i.stack.imgur.com/31SBv.png

https://i.stack.imgur.com/5MGgc.png

【问题讨论】:

  • 您没有向我们展示您是如何发送电子邮件的。那个代码在哪里?注意:不要将这些小部件添加到您的表单中,它们是多余的,为什么还要有这些空属性?
  • 感谢您的评论,我已经修复了上图中的代码。但是我仍然遇到同样的错误。当我发送它时,我无法在我的电子邮件中收到完整的消息。
  • 查看send_mail 的参数顺序。您的订单有误。

标签: python django forms contacts


【解决方案1】:

来自Django Docs

send_mail(
    'Subject here',
    'Here is the message.',
    'from@example.com',
    ['to@example.com'],
    fail_silently=False,
)

如您所见,您在错误的地方写消息和电子邮件。换个地方应该能解决问题。

name 是您的主题,email 是发件人部分,message 是邮件内容。

【讨论】:

  • 谢谢,我编辑了上图的视图代码。现在的问题是我无法在我的 gmail 帐户上显示 emailFrom。我怎样才能修复我的代码,以便我能够看到发件人和收件人的电子邮件?
  • @MarcoEHurtado 你不能直接在 send_mail 中发送emailFrom,它是一个表单对象。请改用form.cleaned_data['message']
【解决方案2】:

尝试将'subject': forms.TextInput(attrs={'': ''}) 添加到您的widgets 字典中,类似于您的表单。他们似乎正在发生碰撞。

【讨论】:

    猜你喜欢
    • 2020-12-30
    • 2017-11-23
    • 2014-05-29
    • 2019-12-09
    • 1970-01-01
    • 2021-07-20
    • 2012-11-15
    • 2017-12-16
    • 2015-04-13
    相关资源
    最近更新 更多