python - 在登录重定向没有发生 django
问题描述
在我的本地主机(127.0.0.1:8000)上,我配置了一个登录页面,登录后它不会重定向到“自动化页面(form_name_view”)。
注意:-当我单击登录按钮时,无论使用正确的凭据还是错误的,都不会发生任何事情。
在views.py
from django.contrib.auth import authenticate,login,logout
# Create your views here.
def login_view(request):
context = {}
if request.method == "post":
username = request.post['username']
password = request.post['password']
user = authenticate(request, username=username, password=password)
if user:
login(request, user)
return HttpResponseRedirect(reverse('IP form'))
else:
context["error"] = "Provide valid credentials"
return render (request,"first_app/login.html", context)
else:
return render (request,"first_app/login.html", context)
def form_name_view(request): #this is the view to which i want to redirect
if request.method == "POST":
#some code
在模型.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Login(models.Model):
username = models.CharField(max_length=50,)
password = models.CharField(max_length=32,)
def __str__(self):
return self.user.Username
在 admin.py
from django.contrib import admin
from first_app.models import Login
# Register your models here.
admin.site.register(Login)
在 login.html 中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login</title>
</head>
<body>
<h1> Please Login</h1>
<form method="post">
{% csrf_token %}
<table>
<tr>
<td><label for="username">Enter username: </label></td>
<td><input type="text" name="username" id="username" required></td>
</tr>
<tr>
<td><label for="username">Enter password: </label></td>
<td><input type="password" name="password" id="password" required></td>
</tr>
<p> {{ error }} </p>
</table>
<input type="submit" value="LOGIN"/>
</form>
</body>
</html>
在 urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from first_app import views
urlpatterns = [
path('Automation_page/', views.form_name_view,name='IP form'),
path('admin/', admin.site.urls),
path('',views.login_view,name='login'),
path('first_app/',include('first_app.urls')),
]
我想要的是:- A)只有用户名在 db 中的用户才能访问自动化页面(form_name_view)
B)当用户登录并成功时,必须将其重定向到自动化页面(form_name_view),否则页面会显示错误消息并停留在登录页面上。
提前谢谢
解决方案
您需要注意字符串和变量的大小写。POST
在 django 中大写:
- 它是
if request.method == 'POST'
- 它是
username = request.POST['username']