Search code examples
python-2.7django-1.9

form validation in django for checking unique emails


This looks like a basic problem which I have not been able to solve.I have a simple HTML page with just a text box and a submit button.The text box is supposed to take email ids from users and store it in the DB upon clicking the submit button.Apart from the normal email format validation,I also need to check if the email already exists in the DB and then inform the user.My code is as follows:

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>

This saves emails in the DB upon clicking the submit button.However,it never checks for existing email ids and my DB has lots of duplicate ids.What am i doing wrong ?


Solution

  • from.is_valid() not call your check_duplicate_email() function.
    You can write your custom validation like this:

    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

    For one more example Custom form validation