如何在表单中获取表单字段值并发送邮件

时间:2019-04-10 09:57:01

标签: django forms web-applications view django-class-based-views

Django 2.2版

我在forms.py中有如下表格

class NameForm(forms.Form):
    email_address = forms.EmailField(label='Your Email Address', max_length=100)

in form.html

<form  method="POST">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>

views.py

def register(request):
    model = Test
    if request.method == 'POST':  # If the form has been submitted...
        form = NameForm(request.POST)  # A form bound to the POST data
        if form.is_valid():  # All validation rules pass

            email_address = form.cleaned_data['email_address']
            print (email_address)
            if (email_address == Test.email_address):

                return HttpResponseRedirect('../success') # Redirect after POST
            else :
                return HttpResponseRedirect('../failed')
    else:
        form = NameForm()  # An unbound form

    return render(request, 'form.html', {'form': form})

models.py

class Test(models.Model)
email_address= models.EmailField(max_length=100)

所有相应模块均已成功导入,并且表单提交没有任何问题。

我需要做的是,当用户使用表格提供电子邮件地址时,必须使用之前提供的database(models.py)中的电子邮件检查电子邮件地址。在检查数据库中的电子邮件地址之后,如果提供的电子邮件地址与数据库中的电子邮件ID匹配,则必须将电子邮件发送到电子邮件ID。逻辑很简单,但是在类视图表单中访问和使用form.field值失败。

我尝试了以下代码

testmail = form.cleaned_data['email_address']
if (testmaill == 'mymail@database.com' ): 
  return HttpResponseRedirect('../success') 

那没有用

1 个答案:

答案 0 :(得分:2)

您可以在表单中进行验证。查看更多信息https://docs.djangoproject.com/en/2.2/ref/forms/validation/

示例:

def clean_email_address(self):
        email_address = self.cleaned_data.get('email_address')
        if Test.objects.filter(email_address__iexact=email_address).count() == 0:
            raise forms.ValidationError("Your email address not exist")

        return email_address

然后在您认为表格有效的情况下,您将获得一个电子邮件地址:

 form.cleaned_data.get("email_address")

您还可以查看提供了哪些数据。

form.data.get("email_address")

这是您编辑的功能:

def register(request):
    if request.method == 'POST':  # If the form has been submitted...
        form = NameForm(request.POST)  # A form bound to the POST data
        if form.is_valid():  # All validation rules pass

            email_address = form.cleaned_data.get('email_address')
            if Test.objects.filter(email_address__iexact=email_address).count() == 0:

                return HttpResponseRedirect('../success') # Redirect after POST
            else :
                return HttpResponseRedirect('../failed')
    else:
        form = NameForm()  # An unbound form

    return render(request, 'form.html', {'form': form})