如何让django用电子邮件代替用户名注册用户 [英] How to make django register users with emails instead of username

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

问题描述

我正在尝试创建一个使用名字,姓氏,电子邮件和密码注册用户的网站.我尝试编写此表单并在视图中使用它

I am trying to make a website that registers users with first name, last name, email, and password. I have tried writing this form and using it in the views

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm


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

    class Meta:
        model = User
        fields = (
            'first_name',
            'last_name',
            'email',
            'password1',
            'password2',
        )

    def save(self, commit=True):
        user = super(RegisterationForm, 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.shortcuts import render, redirect
from Users.forms import RegisterationForm
from django.contrib.auth import authenticate, login




def home(request):
    return render(request, 'Users/index.html')


def register (request):
    if request.method == 'POST':
        form = RegisterationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/map_page/')
    else:
        form = RegisterationForm()
        args = {'form': form}
        return render(request, 'Users/index.html', args)

但是,当我这样做时,我填写了一个错误唯一性约束失败:auth_user.username

However when I do it this way and I fill it in I get an error of UNIQUE constraint failed: auth_user.username

我想知道是否有一种方法可以不使用用户名,而是让他们注册并使用密码和电子邮件登录.

I was wondering if there is a way to not use a username and have them signup and login with password and email.

我尝试过制作一个后端并将其包含在设置中,但这没有用.然后,我也尝试使用自定义模型,并将其包含在admin.py中.我还将它包含在设置中,它给了我一些奇怪的错误.

I have tried making a backend and included it in the settings and that did not work. Then I have also tried using custom models and included that in the admin.py. I have also included it in the settings, and it gives me weird errors.

如何以一种简单的方式用电子邮件而不是用户名注册用户?

How can I register users with email instead of username, in a simple way?

推荐答案

我认为最简单的解决方法是设置 user.username = user.email .

I think the most simple fix is that you set user.username = user.email.

大多数情况下,此问题是由空用户名引起的,第一个用户可以,但第二个用户唯一的失败.

Mostly this issue is caused by empty username, which is okay for the first user, but unique fail for the 2nd user.

另一种选择是从用户模型"中删除字段用户名.

Another option is that you remove the field username from User model.

https://docs.djangoproject.com/en/2.0/topic/auth/customizing/

<代码>类CustomUser(User):用户名=无

这篇关于如何让django用电子邮件代替用户名注册用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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