Search code examples
djangoauthenticationdjango-viewsdjango-users

Django user login error using User authentication()


I have a basic login, sign up html page in my Django project: the login page redirects to the user_login function in views.py as follows:

  <form action="{% url 'user_login' %}" method="POST">. //rest of the code

In urls.py the request is getting forwaded correctly:

   .......#beginnning code

   path('user_login', views.user_login, name='user_login'),
   path('portfolio', views.portfolio, name='portfolio'),  
   ......

In views.py this is my user_login code to authenticate the user and redirect the user to a 'portfolio.html' page if the user credentials are correct.

I have imported User, Login class as follows:

   from django.http import HttpResponseRedirect
   from django.shortcuts import render
   from .models import Profile
   from django.contrib.auth.models import User
   from django.contrib.auth import authenticate, login

   # Create your views here.


   def index(request):
       return render(request, 'mysite/index.html')


   def user_login(request):
       if request.method == 'POST':
           name_r = request.POST.get('name')
           password_r = request.POST.get('password')

           user = authenticate(username=name_r, password=password_r)

           if user:
               login(request, user)

               #below line might be incorrect
               return HttpResponseRedirect('mysite/portfolio.html')
           else:
               return render(request, 'mysite/login.html')

 #rest of the code for signup which is working perfectly.

Whenever i click on Login page, the login page never loads in the first place, let alone checking whether authentication is taking place or not.

The error occurring is as follows:

enter image description here

I am not sure exactly where the error is occurring and what solution must be applied to it.


Solution

  • Your view never returns anything if request.method is not POST.