python - 具有唯一电子邮件的 Django auth.user

标签 python django django-authentication

我使用 django.auth 系统并且我有这个:

class RegisterForm(UserCreationForm):
    username = forms.RegexField(label= "Username" , max_length = 30, regex = r'^[\w]+$', error_messages = {'invalid': "This value may contain only letters, numbers and _ characters."})
    email = forms.EmailField(label = "Email")
    first_name = forms.CharField(label = "First name", required = False)
    last_name = forms.CharField(label = "Last name", required = False)

    class Meta:
        model = User
        fields = ("username", "first_name", "last_name", "email", )

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

我想将电子邮件设置为唯一并检查此验证的表单。我该怎么做?

最佳答案

模型中的某处:

from django.contrib.auth.models import User
User._meta.get_field('email')._unique = True

请注意 unique 之前的下划线。这是实际保存信息的地方。 User._meta.get_field('email').unique 只是一个查看它的 @property

这也适用于 syncdb,因此您将与数据库保持一致。

另请注意,从 Django 1.5 开始,您将不必执行此类操作,因为用户模型将是可插入的。

关于python - 具有唯一电子邮件的 Django auth.user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5773970/

相关文章:

Python,循环遍历范围内的列表

python - tqdm progressbar 和 zip 内置不能一起工作

python - 当HTML代码不一致时,如何在python中使用bs4识别正确的td标签

Django:密码字段 "This field is required"错误

python - Pandas:根据特定列值重置增量

python - 是否可以从 Django 服务器端检测浏览器版本?

django - 使用 Django 将 404 Not Found 页面记录到 Sentry

python-3.x - 在 Python 3 上的 Django 中使用 Google Site Verification API

Django/Auth : logout clears the session data?

python - Django 自定义用户在同步数据库时在运行时遇到导入问题