Django 1.9 检查电子邮件是否已经存在 [英] Django 1.9 check if email already exists

查看:26
本文介绍了Django 1.9 检查电子邮件是否已经存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站设置为没有用户名(或者更确切地说是 user.username = user.email).如果用户尝试输入数据库中已有的用户名,Django 会显示错误消息,但是由于我没有使用用户名进行注册,因此我不知道如何执行此操作.

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.

就像默认设置一样,我不想重新加载页面以查看是否有已与用户关联的电子邮件地址.我的猜测是使用 Ajax,但我不知道如何去做.我看过其他帖子,但最近似乎没有任何内容.

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.

如何检查电子邮件地址是否已存在,如果存在,则给出错误消息,让用户输入新的电子邮件地址?

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?

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:

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 %}

推荐答案

您可以覆盖 UserForm 上的 clean_() 方法来检查这个特定的案件.它看起来像这样:

You can override the clean_<INSERT_FIELD_HERE>() method on the UserForm to check against this particular case. It'd look something like this:

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 文档 关于表单.

You can read more about cleaning specific fields in a form in the Django documentation about forms.

也就是说,我认为您应该考虑创建一个 自定义用户模型,而不是将您的 User Profile 类视为 User 的包装器.

That said, I think you should look into creating a custom user model instead of treating your User Profile class as a wrapper for User.

这篇关于Django 1.9 检查电子邮件是否已经存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆