django中的表单验证用于检查唯一的电子邮件

时间:2016-04-05 08:16:42

标签: python-2.7 django-1.9

这看起来像是一个我无法解决的基本问题。我有一个简单的HTML页面,只有一个文本框和一个提交按钮。文本框应该从用户那里获取电子邮件ID并将其存储在单击提交按钮时的数据库。除了正常的电子邮件格式验证,我还需要检查数据库中是否已存在该电子邮件,然后通知用户。我的代码如下:

models.py

from __future__ import unicode_literals
from django.db import models


class NotificationEmail(models.Model):
    email = models.EmailField(max_length=200)
    created = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return u'%s' % self.email

forms.py

from django import forms
from home.models import NotificationEmail

class NotifyForm(forms.ModelForm):
    class Meta:
        model = NotificationEmail
        fields = ['email']

    def check_duplicate_email(self):
        data = self.cleaned_data['email']
        if NotificationEmail.objects.filter(email=data).exists():
            raise forms.ValidationError('Your email is already in our list of users to be notified.Try a new email')

views.py

from django.shortcuts import render
from forms import NotifyForm

def notify(request):
    if request.method == 'POST':
        form = NotifyForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = NotifyForm()

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

的index.html

<form class="form-horizontal" method="POST" action ="">
    {% csrf_token %}
    <button type="submit">Notify Me</button>
    {{form.email}}
</form>

这会在点击提交按钮时保存数据库中的电子邮件。但是,它从不检查现有的电子邮件ID,而且我的数据库有很多重复的ID。我做错了什么?

2 个答案:

答案 0 :(得分:1)

您可以在电子邮件字段中使用unique=True flag

email = models.EmailField(max_length=200, unique=True)

答案 1 :(得分:1)

from.is_valid()不会调用check_duplicate_email()函数 您可以像这样编写自定义验证:

  

def clean_email(self): data = self.cleaned_data['email'] if User.objects.filter(email=data).count() > 0: raise forms.ValidationError("We have a user with this user email-id") return data

再举一个例子 Custom form validation