问题描述:

I have written a custom form for the creation of a user.

The login works for the users created on the terminal with "python manage.py createsuperuser", but it doesn't work for the users created on the website. I have checked, and the creation form works; I mean, the user is created.

This is the form

class CustomUserCreationForm(UserCreationForm):

"""

A form that creates a user, with no privileges, from the given email and password.

"""

def __init__(self, *args, **kwargs):

super(CustomUserCreationForm, self).__init__(*args, **kwargs)

class Meta:

model = CustomUser

fields = ("email",)

The model

class CustomUser(AbstractBaseUser, PermissionsMixin):

username = models.CharField(max_length=254, unique=True, null=True)

first_name = models.CharField(max_length=254, blank=True)

second_name = models.CharField(max_length=254, blank=True)

email = models.EmailField(blank=True, unique=True)

address1 = models.CharField(max_length=254, blank=True)

address2 = models.CharField(max_length=254, blank=True)

area_code = models.CharField(max_length=20, blank=True)

country_code = models.CharField(max_length=10, blank=True)

date_joined = models.DateTimeField(_('date joined'), default=datetime.now())

is_active = models.BooleanField(default=True)

is_admin = models.BooleanField(default=False)

is_staff = models.BooleanField(default=False)

USERNAME_FIELD = 'email'

REQUIRED_FIELDS = ['username', 'address1', 'address2', 'area_code', 'country_code']

objects = CustomUserManager()

class Meta:

verbose_name = _('user')

verbose_name_plural = _('users')

def get_absolute_url(self):

return "/users/%s" % urlquote(self.email)

def get_full_name(self):

"""

Returns the first_name plus the last_name, with a space in between.

"""

return full_name.strip()

def get_short_name(self):

"""

Returns the first name for the user.

"""

return self.first_name

def email_user(self, subject, message, from_email=None):

"""

Sends an email to this user.

"""

send_email(subject, message, from_email, [self.email])

The register view

def register(request):

registered = False

if request.method == 'POST':

user_form = CustomUserCreationForm(data=request.POST)

if user_form.is_valid():

user = user_form.save()

user.set_password(user.password)

user.save()

registered = True

else:

print user_form.errors

else:

user_form = CustomUserCreationForm()

return render(request, 'register.html', {'user_form': user_form, 'registered': registered})

The login view

def login(request):

if request.method == 'POST':

login_form = CustomUserLoginForm(data=request.POST)

username = request.POST.get('username')

password = request.POST.get('password')

user = auth.authenticate(username=username, password=password)

if user:

if user.is_active:

auth.login(request, user)

return HttpResponseRedirect('/')

else:

return HttpResponse("Your account is disabled.")

else:

print "Invalid login details: {0}, {1}".format(username, password)

return HttpResponse("Invalid login details supplied. Get back to the <a href=\"/\">homepage</a>.")

else:

login_form = CustomUserLoginForm()

return render(request, 'login.html', {'login_form': login_form})

What am I missing here?

Thanks!

网友答案:

First fix the class:

class CustomUser(AbstractUser, PermissionsMixin):

AbstractUser is a real User Model, the BaseUser is just the meta class.

To create a new user you should use this line, in the form or in the register view:

User.objects.create_user(username=username,email=email,password=password)

Note that set_password is used to change the password, and it logs out this user after the password changes.

相关阅读:
Top