使用django.contrib.auth中的表单和视图的用户名动态初始值 [英] Dynamic initial value for the username using forms and views from django.contrib.auth

查看:96
本文介绍了使用django.contrib.auth中的表单和视图的用户名动态初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 login 视图和 django.contrib的 AuthenticationForm 。 auth.views 来登录用户。

I am presently using the login view and the AuthenticationForm from django.contrib.auth.views to login users.

现在,我想扩展此解决方案以预先填充用户名请求对象中的code>字段(如果访问者在其他地方进行了身份验证,则可以推断出用户名)。因为我很懒,并且希望保持 dry ,所以我想知道是否可以在不复制整个登录视图代码的情况下做到这一点。

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.

我知道动态初始值在Django中,但是我看不到如何将它们传递到登录视图(不接受表单实例作为参数)。
在IRC频道上,建议我扩展 AuthenticationForm 来处理请求,但是(据我所知),请求不是总是传递给表单(仅当

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 the AuthenticationForm to process the request, however (as far as I understand), the request is not always passed on to the form (rather only when the form is submitted, which would be too late).

我能想到的唯一替代方法是编写一个自定义登录视图以添加初始值,这基本上可以复制 contrib.auth 包中的代码(以及将初始值传递给表单)。

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!

推荐答案

请求传递到GET的表单中-参见django的第54行。 contrib.auth.views。因此,是的,扩展表单以使用用户名似乎是最好的方法。像(未测试):

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)

这篇关于使用django.contrib.auth中的表单和视图的用户名动态初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆