Skip to main content
 首页 » 编程设计

python之Django 联系表确认电子邮件

2025年05月04日65lyj

我对 Django 和构建我的第一个应用程序还比较陌生。

尝试在网站上搜索,但终究找不到所需的相关信息。

我希望将确认电子邮件发送到联系表中输入的电子邮件地址。我见过发送到选定地址或用户的示例,但我似乎无法弄清楚如何将邮件发送到表单中输入的电子邮件。

非常感谢任何帮助!

models.py:

from django.db import models 
 
class Quote(models.Model): 
    name = models.CharField(max_length=200, blank=False, null=False, verbose_name="your name") 
    email = models.EmailField(max_length=255, blank=False, null=False) 
 
    created_at = models.DateTimeField(auto_now=True) 
 
    def __unicode__(self): 
        return self.name 

forms.py:

class QuoteForm(forms.ModelForm): 
    class Meta: 
        model = Quote 

views.py:

class QuoteView(CreateView): 
    model = Quote 
    form_class = QuoteForm 
    template_name = "quote/quote.html" 
    success_url = "/quote/success/" 
 
    def form_valid(self, form): 
        super(QuoteView,self).form_valid(form) 
        return HttpResponseRedirect(self.get_success_url()) 
 
class QuoteSuccessView(TemplateView): 
    template_name = "quote/quote-complete.html" 

请您参考如下方法:

您可以通过 cleaned_data 属性访问经过验证的表单数据(强制转换为相应类型的字段),如表单文档中所示 https://docs.djangoproject.com/en/dev/topics/forms/#processing-the-data-from-a-form

from django.core.mail import send_mail 
 
 
def form_valid(self, form): 
    super(QuoteView,self).form_valid(form) 
    send_mail("Foo", "bar", 'from@example.com', [form.cleaned_data['email']]) 
    return HttpResponseRedirect(self.get_success_url())