4

I have written a custom auth backend by extending the defalut ModelBackend. Is it possible to send a custom error message to login screen? As of now it is displaying the default message.

2 Answers 2

5

You can raise a django ValidationError

from django.core.exceptions import ValidationError

raise ValidationError("Some custom message")

You can then display it with:

{{ form.non_field_errors|striptags }}
Sign up to request clarification or add additional context in comments.

3 Comments

Note that according to the Django docs your backend should function as following; "check the credentials it gets, and it should return a User object that matches those credentials, if the credentials are valid. If they’re not valid, it should return None". Not sure if you were suggesting to raise a ValidationError in the backend, but I'm just putting it out there.
@Bono, though you're right (and I like your music), facing the alternative of having to implement your own form, simply raising a ValidationError within the auth method is awfully simple and just works.
(of course, the idea is not to throw this for when a user enters "wrong" credentials as-in ones that don't match an existing user, but "wrong" in a sense that is considered invalid because of some other validation logic pertinent for this particular auth backend)
1

The error messages are coming as ValidationError exceptions raised by django.contrib.auth.forms.AuthenticationForm. You would need to extend the Authentication Form or implement your own authentication form to change it's error messages.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.