On Aug 19, 8:19 am, Antonio Ognio <
gnr...@gmail.com> wrote:
> In the login form I ask the user to type an e-mail address and then I
> wrap the view at django.contrib.auth.views.login with another view
> that copies the POST QueryDict of the request in order to make it
> mutable and have the username prepared as needed. It's a bit of an
> ugly hack but for now it works.
You wouldn't need to use that hack if you were using a custom
authentication backend, as `username` would point to whatever you
like, in your case an email.
> My problems have started when I realized I could log in as both
>
j...@company.com and john_company_com with the current approach so I
> wanted to replace the login form with a custom form in which the
> username field has been turned into an email field implemented using a
> proper forms.EmailField field.
Again, with a custom auth backend, you could fully control what you
can login with: a user name, an email, or both. Or even a social
security number, a date or whatever.
> The issue is django.contrib.auth.views.login doesn't accept a custom
> form as parameter only a custom template so I'm kind of forced to copy
> and paste 27 lines of Django internal code into a custom view to
> essentially use my own custom form because currently the form is
> hardcoded to be django.contrib.auth.forms.AuthenticationForm.
If you don't feel like copying the whole view, you can go by monkey-
patching the form, much cleaner in my opinion:
AuthenticationForm.base_fields['username'].max_length = 75
Without it, the standard login view will still work with emails, but
not with those longer than 30 characters (that is, the limit for the
standard username behaviour).
> I could move completely to using an alternative authentication backend
> but the main reason I haven't already do it because of the admin
> preventing me from logging-in with my email address even if the
> authentication backend would accept it. The ticket for this bug is
> #8342.
If you were using a custom backend then you'd have no problem logging
in the admin. That ticket suggests a fix for a misleading error
message that is displayed when login fails, and which assumes you
can't login with an email (that is the default behaviour). So this is
not a bug, but more like a proposal for making things more flexible to
customise.
> Yes, I know there are patches for both issues but I really want to
> avoid depending on a patched Django.
You should really use a custom backend. Very easy to set up, and it
would cleanly fix most of the problems you describe here. The monkey-
patch I mentioned above would fix it for long emails. With those you
should be sorted, even if these tickets don't make it into 1.0.