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

form validation in django for checking unique emails

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

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>

这会在单击提交后将电子邮件保存在数据库中 button.However,它从不检查现有的电子邮件 ID 并且我的数据库有很多重复项 ids.What 我做错了吗?

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

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

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