bugfix> python > 投稿

ユーザー名とパスワードを挿入すると、ホームページにリダイレクトされず、ログインページにとどまり、URLにそのようなメッセージが表示されます

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

Powershellでは、このように表示されます

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...

エラーはありませんが、期待どおりに動作しません。

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})

テンプレート

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 %}