Authenticate with Django 1.5
Posted
by
gorjuce
on Programmers
See other posts from Programmers
or by gorjuce
Published on 2012-12-15T20:17:27Z
Indexed on
2012/12/15
23:18 UTC
Read the original article
Hit count: 223
I'm currently testing django 1.5 and a custom User model, but I've some problems. I've created a User class in my account app, which looks like:
class User(AbstractBaseUser):
email = models.EmailField()
activation_key = models.CharField(max_length=255)
is_active = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
I can correctly register a user, who is stored in my account_user table. Now, how can I log in? I've tried with:
def login(request):
form = AuthenticationForm()
if request.method == 'POST':
form = AuthenticationForm(request.POST)
email = request.POST['username']
password = request.POST['password']
user = authenticate(username=email, password=password)
if user is not None:
if user.is_active:
login(user)
else:
message = 'disabled account, check validation email'
return render(
request,
'account-login-failed.html',
{'message': message}
)
return render(request, 'account-login.html', {'form': form})
I can correctly register a new User
My forms.py which contains my register form
class RegisterForm(forms.ModelForm):
""" a form to create user"""
password = forms.CharField(
label="Password",
widget=forms.PasswordInput()
)
password_confirm = forms.CharField(
label="Password Repeat",
widget=forms.PasswordInput()
)
class Meta:
model = User
exclude = ('last_login', 'activation_key')
def clean_password_confirm(self):
password = self.cleaned_data.get("password")
password_confirm = self.cleaned_data.get("password_confirm")
if password and password_confirm and password != password_confirm:
raise forms.ValidationError("Password don't math")
return password_confirm
def clean_email(self):
if User.objects.filter(email__iexact=self.cleaned_data.get("email")):
raise forms.ValidationError("email already exists")
return self.cleaned_data['email']
def save(self):
user = super(RegisterForm, self).save(commit=False)
user.password = self.cleaned_data['password']
user.activation_key = generate_sha1(user.email)
user.save()
return user
My question is: Why does authenticate give me None
? I know I'm trying to authenticate()
with an email as username but is that not one of the reasons to use a custom User model?
© Programmers or respective owner