I am presently using the login
view and the AuthenticationForm
from django.contrib.auth.views
to login users.
Now, I would like to extend this solution to prepopulate the username
field from the request
object (I can infer the username if visitors are authenticated elsewhere). Because I am lazy and would like to keep dry, I wonder if this is possible without replicating the entire login view code.
I am aware of dynamic initial values in Django, but I cannot see how these might be passed into the login view (which does not accept form instances as parameter).
On the IRC channel, it was suggested that I extend theAuthenticationForm
to process the request, however (as far as I understand), the reque开发者_如何学运维st is not always passed on to the form (rather only when the form is submitted, which would be too late).
The only alternative I can think of is writing a custom login view to add initial values, which would basically replicate the code from the contrib.auth
package (plus passing initial values to the form).
My question, then, is this: Is there a simpler alternative, one that would get by without copying code? Any hints would be much appreciated. Thanks!
The request is passed into the form on GET - see line 54 of django.contrib.auth.views. So yes, extending the form to take the username seems like the best way to go. Something like (untested):
class ExtendedAuthForm(AuthenticationForm):
def __init__(self, request=None, *args, **kwargs):
if request is not None:
username = request.get_username_however()
initial = kwargs.get('initial', {})
initial_default = {'username': username}
initial_default.update(initial)
kwargs['initial'] = initial_default
super(ExtendedAuthForm, self).__init__(request, *args, **kwargs)
精彩评论