我的 urls.py 是这样的:
from django.conf.urls import url
from django.views.generic import ListView, TemplateView
from .models import Dreamreal
from . import views
urlpatterns = [
url(r'^connection/login/$', views.login),
url(r'^connection/$', TemplateView.as_view(template_name =
'login.html')),
url(r'^login/$', views.login, name = 'login')
]
我的 views.py 是:
from .forms import LoginForm
from . import models
def login(request):
username = "not logged in"
if request.POST:
# GET THE POSTED FORM
MyLoginForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
username = MyLoginForm.cleaned_data['username']
else:
MyLoginForm = LoginForm()
return render(request, 'loggedin.html', {'username' : username})
我的 forms.py 是:
from django import forms
from .models import Dreamreal
class LoginForm(forms.Form):
username = forms.CharField(max_length = 100)
password = forms.CharField(widget = forms.PasswordInput())
# METHOD TO VERIFY IF USER IS IN DB
def clean_message(self):
username = self.cleaned_data.get("username")
dbuser = Dreamreal.objects.filter(name = 'username')
if not dbuser:
raise forms.ValidationError("User does not exist in our db!")
return username
我的 models.py 是:
from django.db import models
class Dreamreal(models.Model):
website = models.CharField(max_length = 50)
mail = models.CharField(max_length = 50)
name = models.CharField(max_length = 50)
phonenumber = models.IntegerField()
class Meta:
db_table = 'dreamreal'
我的 login.html 是:
<html>
<head>
<title>LOG IN</title>
</head>
<body>
<form name="form" action="/connection/login/" method="POST">
{% csrf_token %}
<div style="max-width: 470px;">
<center><input type="text" name="username"
placeholder="username" style="margin-left: 20%;" required>
</center>
</div>
<br>
<div style="max-width: 470px;">
<center><input type="password" name="password"
placeholder="password" style="margin-left: 20%;"></center>
</div>
<br>
<div style="max-width: 470px;">
<center><button style = "border:0px; background-color:#4285F4;
margin-top:8%; height:35px; width:80%;margin-left:19%;" type =
"submit" value = "Login" >
<strong>Login</strong>
</button></center>
</div>
</form>
</body>
</html>
我的 loggedin.html 是:
{% extends 'base.html' %}
<html>
<head>
<title>{% block title%}{{ username }}{% endblock %}</title>
</head>
<body>
{% block content %}
You are : <strong>{{ username }}</strong>
{% endblock %}
当我运行代码,然后在/ connection / url的dield输入中输入名称和密码时,它会重定向到/ connectionlogin / url但显示我在表单中输入的所有用户名都有效,而不应该仅显示存储在数据库名称 Dreamreal 中的名称。 有人请帮忙!
答案 0 :(得分:0)
您正在验证username
字段,因此您应该为方法clean_username
命名。如果表单有一个名为clean_message
的字段,Django只会调用message
字段。
要查看模板中的任何表单错误,您需要在调用render时在上下文中包含表单:
return render(request, 'loggedin.html', {'username' : username, 'form': MyLoginForm}
除非您在模板中使用form
,否则您无法在模板中看到错误。最简单的方法是包含{{ form }}
。如果您需要执行更高级的操作,请参阅working with forms上的文档。