Reputation: 91630
Should I write authentication logic in my forms for handling user login?
For example, I'd like to display messages to the user if an account hasn't been activated yet. For that, I'm currently doing something like this (terrible, I know):
def login(request):
email = request.POST.get('email')
password = request.POST.get('password')
user = auth.authenticate(email=email, password=password)
if user is not None:
if user.is_active:
auth.login(request, user)
# etc
else:
# send "not activated message"
else:
# send "not found message"
It's a lot uglier than that in implementation, but I'll save the internet from my initial attempt at form processing at Django before I learned the forms API.
In any case, it's important to be able to tell users that their accounts aren't active yet if they try to log in, that way they can at least know what to do next. The forms API seems to make the most sense here: I could perform simple email address and password validation, then perform actual account activation logic validation in the clean()
method on my form and send them a message if there's an issue.
Are there any downsides to doing this?
PS: I know that Django ships with a login view and the whole nine yards, but I have specific project needs in which I need to tweak things quite a bit with authentication etc., so please don't suggest to "use the included view," I can't this time.
Upvotes: 0
Views: 170
Reputation: 6756
Like you wrote you can create a login form in which you can add clean method:
class LoginForm(forms.Form):
email = ...
password = ...
def clean(self):
user = User.objects.filter(email=self.email)
if not user.exists():
raise forms.ValidationError("User does not exists")
if not user.is_active:
raise forms.ValidationError("This account is not active")
It is a good way for handling this issue.
Upvotes: 1