使用户电子邮件唯一django [英] Make User email unique django

查看:69
本文介绍了使用户电子邮件唯一django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户注册时,如何使Django用户电子邮件变得唯一?

How can I make a Django User email unique when a user is signing up?

forms.py

class SignUpForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2")

    def save(self, commit=True):
        user = super(SignUpForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user

我正在使用from django.contrib.auth.models用户。
我是否需要在模型中覆盖用户。当前,该模型未引用用户。

I'm using the from django.contrib.auth.models User. Do I need to override the User in the model. Currently the model doesn't make a reference to User.

views.py

class SignUp(generic.CreateView):
    form_class = SignUpForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'


推荐答案

最好的答案是使用 CustomUser 通过将 AbstractUser 子类化,然后在其中放置唯一的电子邮件地址。例如:

The best answer is to use CustomUser by subclassing the AbstractUser and put the unique email address there. For example:

from django.contrib.auth.models import AbstractUser


class CustomUser(AbstractUser):
    email = models.EmailField(unique=True)

并更新使用 AUTH_USER_MODEL = app.CustomUser 进行设置。

但是如果您不必存储唯一电子邮件或可能不将其用作用户名字段,则可以更新表单的 clean 方法以进行验证。例如:

But if its not necessary for you to store the unique email in Database or maybe not use it as username field, then you can update the form's clean method to put a validation. For example:

class YourForm(UserCreationForm):

    def clean(self):
       email = self.cleaned_data.get('email')
       if User.objects.filter(email=email).exists():
            raise ValidationError("Email exists")
       return self.cleaned_data



更新



如果在中间项目中,则可以按照文档有关如何更改迁移,简而言之是:

Update

If you are in mid project, then you can follow the documentation on how to change migration, in short which is to:


  1. 备份数据库

  2. 创建一个与auth.User相同的自定义用户模型,将其命名为User(这样,许多表保持相同的名称)并设置db_table ='auth_user'(因此它使用相同表)

  3. 删除所有迁移文件( __ init __。py 除外)

  4. 删除表 django_migrations
  5. 中的所有条目
  6. 使用 python manage.py makemigrations

  7. 通过 python manage.py migration --fake

  8. 取消设置 db_table ,对自定义模型进行其他更改,生成迁移并应用

  1. Backup you DB
  2. Create a custom user model identical to auth.User, call it User (so many-to-many tables keep the same name) and set db_table='auth_user' (so it uses the same table)
  3. Delete all Migrations File(except for __init__.py)
  4. Delete all entry from table django_migrations
  5. Create all migrations file using python manage.py makemigrations
  6. Run fake migrations by python manage.py migrate --fake
  7. Unset db_table, make other changes to the custom model, generate migrations, apply them

但是,如果您只是开始,请删除迁移目录中的数据库和迁移文件,但 __ init __。py 。然后创建一个新的数据库,通过 python manage.py makemigrations 创建新的迁移集,并通过 python manage.py migration

But if you are just starting, then delete the DB and migrations files in migration directory except for __init__.py. Then create a new DB, create new set of migrations by python manage.py makemigrations and apply migrations by python manage.py migrate.

对于其他模型中的引用,您可以将它们引用到 settings.AUTH_USER_MODEL 中以避免将来发生问题。例如:

And for references in other models, you can reference them to settings.AUTH_USER_MODEL to avoid any future problems. For example:

user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING)

它将自动引用当前用户模型。

It will automatically reference to the current User Model.

这篇关于使用户电子邮件唯一django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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