如何通过django中的手机号码或电子邮件地址登录?

时间:2017-06-17 10:15:04

标签: python django python-3.x django-models django-views

我最初习惯使用电子邮件和密码登录,但现在想要更改它,以便我们可以使用手机号码或电子邮件地址和密码登录。我无法理解我的代码中要更改的部分我不想删除已有的用户和数据。

forms.py

from django.contrib.auth.models import User
from django import forms


class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email', 'password']

views.py

class UserFormView(View):

    form_class = UserForm
    template_name = 'main/registration_form.html'

    def get(self, request):
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():

            user = form.save(commit=False)

            # cleaned (normalized) data
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            user.username = email
            user.set_password(password)
            user.save()

            # return user objects if credentials are correct
            user = authenticate(username=email, password=password)

            if user is not None:

                if user.is_active:
                    login(request, user)
                    # request.user.username       display their username
                    return redirect('main:register2')
        return render(request, self.template_name, {'form': form})

class LoginForm(View):

    form_class = UserForm
    template_name = 'main/login_form.html'

    def get(self, request):
        form = self.form_class(None)
        if error:
            return render(request, self.template_name, {'form': form}, 
{'error': error})
        else:
            return render(request, self.template_name, {'form': form})

    def post(self, request):
        email = request.POST.get('email', '')
        password = request.POST.get('password', '')
        user = auth.authenticate(username=email, password=password)

        if user is not None and user.is_active:
            # Correct password, and the user is marked "active"
            auth.login(request, user)
            # Redirect to a success page.
            return HttpResponseRedirect("/main/home/")
        else:
            # Show an error page
            error = True
            return HttpResponseRedirect("/main/", {'error': error})

请考虑一下我是Django新手的事实。在此先感谢:)

1 个答案:

答案 0 :(得分:0)

在视图的post方法中,确定用户为您提供的内容。如果是电子邮件,请使用电子邮件提供Django的authenticate()方法。如果没有,那么假设它是一个电话号码(你也可以在那里运行其他验证)并在验证过程中使用它。

另一种方法是创建一个自定义authenticate()方法,如下所示:

from django.contrib.auth.backends import ModelBackend


class MobilePhoneOrEmailModelBackend(ModelBackend):

    def authenticate(self, username=None, password=None):
        # the username could be either one of the two
        if '@' in username:
            kwargs = {'email': username}
        else:
            kwargs = {'mobile_phone': username}
        try:
            user = User.objects.get(**kwargs)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

    def get_user(self, username):
        try:
            return User.objects.get(pk=username)
        except User.DoesNotExist:
            return None

请告诉我这是否适合您。

此线程中对用户user3282276的信用:Log in user using either email address or username in Django