如何在使用django.views.login时将额外的参数传递给authenticate函数



我有一个身份验证后端,看起来像这个

class Backend(object):
    def authenticate(self, username=None, password=None):
            # Do stuff

我的url处理程序看起来像这个

url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),

登录表单看起来像这样(标准表单,您可以跳过此)

{% if not form.username.errors %}
        <input id="id_username" name="username" type="text" class="form-control" placeholder="Username (admin)" autofocus>
      {% else %}
        <div class="form-group has-error">
          {% for error in form.username.errors %}
            <label class="control-label" for="id_username">{{ error }}</label>
          {% endfor %}
          <input id="id_username" name="username" type="text" class="form-control" placeholder="Username (admin)" autofocus>
        </div>
      {% endif %}
      {% if not form.password.errors %}
        <input id="id_password" name="password" type="text" class="form-control" placeholder="Password (admin)" autofocus>
      {% else %}
        <div class="form-group has-error">
          {% for error in form.password.errors %}
            <label class="control-label" for="id_password">{{ error }}</label>
          {% endfor %}
          <input id="id_password" name="password" type="text" class="form-control" placeholder="Password (admin)">
        </div>
      {% endif %}

我需要从表单中向authenticate函数传递一个额外的参数(例如country)。新的身份验证功能应该像这个

def authenticate(self, username=None, password=None, country=None):

如何做到这一点?

您需要对AuthenticationForm进行子类化,并重写clean方法,以便它使用额外的参数调用authenticate

然后,在urls.py中,将authentication_form传递到登录视图。

我相信您正在询问如何编写自定义身份验证后端并在其中定义自己的authenticate方法。

如果是这样,请查看Django文档。如上所述,authenticate方法是针对身份验证(**凭据)运行的。这意味着您可以传递任何必需的kwargs参数,包括"country"。

在您的情况下:

  1. 将"country"添加到方法声明中
  2. 在"authenticate"用户时,将country作为附加参数传递

就是这样。希望能有所帮助。

最新更新