Home > database >  Unable to login using Django
Unable to login using Django

Time:10-09

This is my login view

def login_request(request):
    if request.method == 'POST':
        username = request.POST.get['username']
        password = request.POST.get['password']

        user = authenticate(username = username, password = password)
        if user is not None:
            form = login(request, user)
            messages.success(request, f' welcome {username} !!')
            return redirect('index')
        else:
            messages.info(request, f'Unable to Login now')

    form = AuthenticationForm()
    context = {'form':form}
    return render(request, "BizzyCardApp/log-in.html", context)

and this is the log-in.html file

{% extends "BizzyCardApp/base.html" %}

{% block content %}

{% load crispy_forms_tags %}

<br>
<br>
<br>
<br>
<br>

<div  id="grad"  style="border-radius: 10%; width: 300px;">  
    <br>
    <form>
    <table >
      <tbody>
        <tr>
          <div >
            <form method="POST">
                {% csrf_token %}
                
                {% for field in form %}
                    <div>
                    <p>{{ field.label }}: <br> {{ field }}</p> 
                    {% for error in field.errors %}
                        <small style="color: red">{{ error }}</small>
                    {% endfor %}
                    </div>
                {% endfor %}
            </form> 
          </div>
        </tr>
        <tr>
          <div >
            <button type="submit" >Submit</button>
          </div>
        </tr>
      </tbody>
    </table>
    </form>
    <div >
      <a href="/sign-up/" >
          Don't have an account? Sign Up
      </a>
    </div>
  </div>

{% endblock %}

Once I hit the Submit button, it's supposed to redirect me to the index page but all that happens is that the GET request is done but there is no response from the backend to redirect. It just stays on the same page and the URL changes to

http://127.0.0.1:8000/login/?csrfmiddlewaretoken=0rkrC5wOe8LDQc9x0s0Zdag45PXRZixJAYaQns3dod58QhUL6OdmTEvZMYdRNTfq&username=tushar&password=abcd123*

CodePudding user response:

Try this login view:

def login_request(request):
    if request.method == 'GET':
        if request.user.is_authenticated:
            return redirect('/index/')
    if request.method=='GET':
        form = loginForm(request.POST)
        if form.is_valid():

            user=authenticate(username=form.cleaned_data['username'],
                              password=form.cleaned_data['password'])
            if user:
                print('user',user)
                login(request,user)
                return redirect('/index/')
            else:
                print('Not authenticated')
    elif request.method=='GET':
        if request.user.is_authenticated:
            return redirect('/index/')
        form=loginForm()
    return render(request,'users/login.html',{'form':form})

In forms.py:

Add this:

class CustomAuthenticationForm(AuthenticationForm):
    def confirm_login_allowed(self, user):
        if not user.is_active or not user.is_validated:
            raise forms.ValidationError('There was a problem with your login.', code='invalid_login')

And in login view, change AuthenticationForm to CustomAuthenticationForm. And import it in login view using below code.

from .form import CustomAuthenticationForm

CodePudding user response:

Finally figured out the answer. The method for the tag wasn't given as POST.

The tag was just and not

The backend kept on getting GET requests instead and that's why the code wasn't working.

This is the Login method code I'm using now


def Login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username = username, password = password)
        if user is not None:
            form = auth_login(request, user)
            messages.success(request, f' welcome {username} !!')
            return redirect('/')
        else:
            messages.info(request, f'account done not exit plz sign in')
    form = AuthenticationForm()
    return render(request,'BizzyCardApp/log-in.html',{'form':form})
  • Related