How to create a user with just First name, Last name and emai. And not with the username

自作多情 提交于 2019-12-11 09:04:56

问题


Is there any way to create a user without the username? I tried doing this by first_name, last_name, password and email. But got an error:

TypeError at /accounts/register/
create_user() takes at least 2 arguments (3 given)

So, I searched for creating so, and then found that django needs a username. But I hope there is some other way around. Can anyone please guide me through if there is. Thank you.


回答1:


If you don't want to use a custom user model you can subclass UserCreationForm and override the username field as such:

from django.contrib.auth.forms import UserCreationForm


class UserCreationForm(UserCreationForm):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'username',)

    username = forms.EmailField(label='Email', max_length=255)

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.email = user.username
        user.save()
        return user

Now you have a UserCreationForm that will validate and use an email address for the username, in addition to setting the email field to the username automatically to keep them in sync. This doesn't set the password field, which you would need to do as well. Change as you need, hope that gets you going.




回答2:


Yes, it is possible. You can override the default User model by substituting a custom User model . Here is the details Substituting a custom User model.

Sample code: models.py

if django.VERSION >= (1, 5):
    from django.contrib.auth.models import AbstractBaseUser

#Identifier is e-mail instead of user ID
class User(AbstractBaseUser):
    email = models.EmailField(max_length=254, unique=True, db_index=True)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

    REQUIRED_FIELDS = ['email']

    def __unicode__(self):
        return self.email


来源:https://stackoverflow.com/questions/18294407/how-to-create-a-user-with-just-first-name-last-name-and-emai-and-not-with-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!