Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django User cannot login

I made a simple register and login script, the register script works and sends the user information to a database but the login does not log the user in.

This is the login function in views.py:

from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from .forms import LoguserForm
# Create your views here.

def loginpage(request):

    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(request, username=username, password=password)

        if user is not None:
           login(request, user)
           return redirect('home')

    context = {}
    return render(request, 'accounts/login.html', context)

This is the login.html file:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<body class="container">

    <div class="loginbox">
        <form id="login" class="input-group">
            {% load static %} <img src="{% static 'accounts/images/logo.png' %}" id="loginlogo">
            {% csrf_token %}
            <input type="text" class="inputfield" name="username" placeholder="Username">
            <input type="password" class="inputfield" name="password" placeholder="Password">
            <input type="submit" class="submitbtn" value="Login"></input>
            {% for message in messages %}
            <p>{{message}}</p>
            {% endfor %}
            <p1 class="registerp">New here? <a href="/register">Register</a></p1>
        </form>
    </div>

This is the homepage code:

def home(request):
    return HttpResponse('Home Page')

When I try to login instead of redirecting me to the home page the URL changes to:

http://127.0.0.1:8000/?csrfmiddlewaretoken=F63yG1ZNQTr4e6tRvjvj5TraSLeDDxAGCm1S89k4yuq21DyPgS4AlnfxA2KtnrA4&username=Tester&password=888tyuuyt

>Solution :

You need to add the operation method as POST and the url in your form tag as shown below.

<form action="your-login-endpoint/" id="login" class="input-group" method="post">
{% csrf_token %}
...
</form>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading