Django 1.9 check if email already exists
<p>My site is set up so there is no username (or rather user.username = user.email). Django has an error message if a user tries to input a username that is already in the database, however since I'm not using a username for registration I can't figure out how to do this. </p>

<p>Just like the default settings already is, I don't want to reload the page to find out if there is an email address already associated with a user. My guess is to use Ajax, but I can't figure out how to do it. Ive looked at other posts, but there doesn't seem to be anything recent. </p>

<p>How can I check to see if an email address already exists, and if so, give an error message for the user to input a new email address?</p>

<p>models.py:</p>

<pre><code>class MyUsers(models.Model):
    user = models.OneToOneField(User)
    first_name = models.CharField(max_length=100, blank=True)
    last_name = models.CharField(max_length=100, blank=True)
    email = models.EmailField(max_length=100, blank=True, unique=True)
    company = models.CharField(max_length=100, blank=True, null=True)
    website = models.URLField(max_length=100, blank=True, null=True)
    phone_number = models.CharField(max_length=100, blank=True, null=True)

    def __str__(self):
        return self.user.username
</code></pre>

<p>forms.py:</p>

<pre><code>class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('email',)


class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('first_name', 'last_name', 'company', 'website', 'phone_number')
</code></pre>

<p>views.py:</p>

<pre><code>def index(request):
    registered = False

    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.password = ""
            user.username = user.email
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user
            profile.email = user.email
            profile.save()

            user.first_name = profile.first_name
            user.last_name = profile.last_name
            user.save()

            registered = True
            return HttpResponseRedirect(reverse('registration'))
        else:
            print user_form.errors, profile_form.errors
    else:
        user_form = UserForm()
        profile_form = UserProfileForm1()

    context = {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}
    return render(request, 'mysite/register.html', context)
</code></pre>

<p>register.html:</p>

<pre><code>{% extends 'mysite/base.html' %}
{% load staticfiles %}

{% block title_block %}
    Register
{% endblock %}

{% block head_block %}
{% endblock %}

{% block body_block %}    
    &lt;form id="user_form" method="post" action="/mysite/" enctype="multipart/form-data"&gt;
        {% csrf_token %}
        {{ user_form.as_p }}
        {{ profile_form.as_p }}

        &lt;input type="submit" name="submit" value="Register" /&gt;
    &lt;/form&gt;
{% endblock %}
</code></pre>

<p>You can override the <code>clean_&lt;INSERT_FIELD_HERE&gt;()</code> method on the <code>UserForm</code> to check against this particular case. It'd look something like this:</p>

<p><em>forms.py:</em></p>

<pre><code>class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('email',)

    def clean_email(self):
        # Get the email
        email = self.cleaned_data.get('email')

        # Check to see if any users already exist with this email as a username.
        try:
            match = User.objects.get(username=email)
        except User.DoesNotExist:
            # Unable to find a user, this is fine
            return email

        # A user was found with this as a username, raise an error.
        raise forms.ValidationError('This email address is already in use.')

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('first_name', 'last_name', 'company', 'website', 'phone_number')
</code></pre>

<p>You can read more about cleaning specific fields in a form in the <a href="https://docs.djangoproject.com/en/1.10/ref/forms/validation/#cleaning-a-specific-field-attribute" rel="nofollow">Django documentation</a> about forms.</p>

<p>That said, I think you should look into creating a <a href="https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#specifying-a-custom-user-model" rel="nofollow">custom user model</a> instead of treating your <code>User Profile</code> class as a wrapper for <code>User</code>.</p>

python ajax django django-forms django-templates