1

我正在尝试创建一个自定义登录表单。以下是我到目前为止所拥有的。我的问题是,无论我做什么,登录都不会进行身份验证。即使我有正确的电子邮件和密码,我总是会得到:

请输入正确的用户名和密码。两个地方都要注意大小写。

我认为这是因为我正在检查电子邮件和密码。

*这是我的表格。*

class EmailAuthenticationForm(AuthenticationForm):
    username = forms.EmailField(label=_('Email Address'))
    redirect_url = forms.CharField(
        widget=forms.HiddenInput, required=False)

    def __init__(self, host=None, *args, **kwargs):
        self.host = host
        super(EmailAuthenticationForm, self).__init__(*args, **kwargs)

这是我的看法。**

class AccountAuthView(FormView):
    template_name = 'accounts/login.html'
    form_class = EmailAuthenticationForm
    redirect_field_name = 'next'

    def get_form_class(self):
        return self.form_class

    def form_valid(self, form):
        auth_login(self.request, form.get_user())
        return HttpResponseRedirect(form.cleaned_data['redirect_url'])

    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated():
            return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
        return super(AccountAuthView, self).get(
            request, *args, **kwargs)
4

2 回答 2

2

是的,这可以很容易地完成,首先创建一个身份验证后端:

后端.py

from django.contrib.auth import get_user_model


class EmailAuthBackend(object):
    """
    Email Authentication Backend
    """

    def authenticate(self, username=None, password=None):
        """ Authenticate a user based on email address as the user name. """
        try:
            user = get_user_model().objects.get(email=username)
            if user.check_password(password):
                return user
        except get_user_model().DoesNotExist:
            return None 

然后在settings.py中:

AUTHENTICATION_BACKENDS = ('backends.EmailAuthBackend',)

最后确保您的表单具有电子邮件字段:

<form action="." method="post">
  {% csrf_token %}
  <input type="hidden" name="next" value="{{ next }}" />
  {{ form.non_field_errors }}
  {% for field in form %}
    <div class="field-wrapper">
      <div class="label-wrapper">
        {% if field.name == "username" %}
          Email address
        {% else %}
          {{ field.label_tag }}
        {% endif %}
        {% if field.field.required %}<span class="required">*</span>{% endif %}
      </div>
      <div class="value-wrapper">
        {{ field }}
        {{ field.errors }}
      </div>
    </div>
  {% endfor %}
  <div class="submit-wrapper">
    <input type="submit" value="Sign In" />
  </div>
</form>
于 2013-10-21T13:04:38.473 回答
1

Django 有一个完整的示例来展示如何进行自定义身份验证。

于 2013-10-21T05:37:22.347 回答