0
votes

when I insert username and password, it doesn't redirect to home page and stays on the login page, and its URL displays such messages

http://localhost:8000/login/?csrfmiddlewaretoken=B6RMXDzgZjnk2QzbmbcesMqsRUOtVH3Q1FBaS1HCB6CXXujpbOziiHLH8VR1oLzC&username=admin&password=laughonloud24

in Powershell, it shows like this

System check identified no issues (0 silenced).
May 25, 2018 - 11:50:07
Django version 2.0.5, using settings 'a.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[25/May/2018 11:50:10] "GET /login/?csrfmiddlewaretoken=B6RMXDzgZjnk2QzbmbcesMqsRUOtVH3Q1FBaS1HCB6CXXujpbOziiHLH8VR1oLzC&username=admin&password=laughonloud24 HTTP/1.1" 200 446
Performing system checks...

there is no error though, but it doesn't behave the way i want it to..

models.py

from django.db import models

# Create your models here.
class login_model(models.Model):
    username = models.CharField(max_length=200)
    password = models.CharField(max_length=200)

forms.py

from django import forms
from .models import login_model

class LoginForm(forms.ModelForm):
    class Meta:
        model = login_model
        fields = ['username','password']

urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('login/',views.login_view,name = 'login_url' ),
    path('',views.home, name = 'home_url'),
]

views.py

from django.shortcuts import render,redirect
from .forms import LoginForm
from django.contrib.auth import authenticate,login
# Create your views here.
def home(request):
    return render(request,'home.html')

def login_view(request):
    if request.method == 'POST':
        form = LoginForm(request.POST or None)
        if form.is_valid():
            uusername = form.cleaned_data.get('username')
            ppassword = form.cleaned_data.get('password')
            user = authenticate(request,username=uusername,password=ppassword)
            if user is None:
                login(request,user)
                return redirect('home url')
            else:
                print('Error')

    else:
        form = LoginForm()
    return render(request,'login.html',{'form':form})

templates

login.html

<form>
    {% csrf_token %}
    {{form.as_p}}
    <input type="submit" value="Login">
</form>

home.html

{% if user.is_authenticated %}
<h1>Hi {{user.username}} </h1>
{% else %}
<h1> Hi Ola Amigo </h1>
<p>Please Login <a href="{% url 'login_url' %}">Login</a> </p>
{% endif %}
1

1 Answers

3
votes

You should set form's method as POST, otherwise it's GET by default:

<form action="" method="post">
    {% csrf_token %}
    {{form.as_p}}
    <input type="submit" value="Login">
</form>