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:
<body >
<div >
<form id="login" >
{% load static %} <img src="{% static 'accounts/images/logo.png' %}" id="loginlogo">
{% csrf_token %}
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Login"></input>
{% for message in messages %}
<p>{{message}}</p>
{% endfor %}
<p1 >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:
CodePudding user response:
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" method="post">
{% csrf_token %}
...
</form>