1

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.

4

2 回答 2

3

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.

于 2013-08-19T13:52:36.270 回答
1

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
于 2013-08-18T05:52:16.250 回答