Log in user using either email address or username in Django

后端 未结 13 2558
故里飘歌
故里飘歌 2020-12-02 08:34

I am trying to create an auth backend to allow my users to log in using either their email address or their username in Django 1.6 with a custom user model. The backend work

13条回答
  •  北海茫月
    2020-12-02 09:09

    Those who are still struggling. Because of following multiple tutorials, we end up with this kind of a mess. Actually there are multiple ways to create login view in Django. I was kinda mixing these solutions in my Django predefined method of log in using

    def login_request(request):
        form = AuthenticationForm()
        return render(request = request,
                  template_name = "main/login.html",
                  context={"form":form})
    

    But now I have worked around this problem by using this simple approach without modifying the authentication backend.

    In root directory (mysite) urls.py

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('accounts/', include('django.contrib.auth.urls')),
    ]
    

    In your app directory urls.py

    urlpatterns = [
        path('accounts/login/', views.login_view, name='login'),
    ]
    

    In views.py

    def login_view(request):
        if request.method == 'POST':
            userinput = request.POST['username']
            try:
                username = User.objects.get(email=userinput).username
            except User.DoesNotExist:
                username = request.POST['username']
            password = request.POST['password']
            user = auth.authenticate(username=username, password=password)
    
            if user is not None:
                auth.login(request, user)
                messages.success(request,"Login successfull")
                return redirect('home')
            else:
                messages.error(request,'Invalid credentials, Please check username/email or password. ')
        return render(request, "registration/login.html")
    

    Finally, In templates (registration/login.html)

    SIGN IN

    {% csrf_token %}
    Forgot Password?

    Don't have an account? REGISTER NOW

    This is the easiest solution I came up with.

提交回复
热议问题