Django 1.9检查电子邮件是否已存在

时间:2016-09-20 17:58:09

标签: python ajax django django-forms django-templates

我的网站已设置,因此没有用户名(或者更确切地说是user.username = user.email)。如果用户尝试输入已存在于数据库中的用户名,Django会出现错误消息,但由于我没有使用用户名进行注册,因此我无法弄清楚如何执行此操作。

就像默认设置一样,我不想重新加载页面以查明是否有与用户关联的电子邮件地址。我的猜测是使用Ajax,但我无法弄清楚如何做到这一点。我看过其他帖子,但似乎没有最近的事情。

如何查看电子邮件地址是否已存在,如果存在,请提供错误消息,以便用户输入新的电子邮件地址?

models.py:

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

forms.py:

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')

views.py:

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)

register.html:

{% extends 'mysite/base.html' %}
{% load staticfiles %}

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

{% block head_block %}
{% endblock %}

{% block body_block %}    
    <form id="user_form" method="post" action="/mysite/" enctype="multipart/form-data">
        {% csrf_token %}
        {{ user_form.as_p }}
        {{ profile_form.as_p }}

        <input type="submit" name="submit" value="Register" />
    </form>
{% endblock %}

1 个答案:

答案 0 :(得分:5)

您可以覆盖clean_<INSERT_FIELD_HERE>()上的UserForm方法来检查此特定情况。它看起来像这样:

forms.py:

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(email=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')

您可以在Django documentation表单中了解有关清除表单中特定字段的详细信息。

那就是说,我认为您应该考虑创建一个custom user model而不是将User Profile类视为User的包装。