my forms.py:
from django import forms
from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.utils.text import capfirst
from .models import Classname, Sectionname, Teachername, Attendancename
class AuthenticationForm(forms.Form):
username = forms.CharField(max_length=20)
password = forms.CharField(widget=forms.PasswordInput)
error_messages = {
'invalid_login': ("Please enter a correct %(username)s and password."
"Note that both fields may be case-sensitive."),
'inactive': ("This account is inactive"),
}
def __init__(self, request=None, *args, **kwargs):
self.request = request
self.user_cache = None
super(AuthenticationForm, self).__init__(*args, **kwargs)
UserModel = get_user_model()
self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
if self.fields['username'].label is None:
self.fields['username'].label = capfirst(self.username_field.verbose_name)
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if username and password:
self.user_cache = authenticate(username=username, password=password)
if self.user_cache is None:
raise forms.ValidationError(
self.error_messages['invalid_login'],
code='invalid_login',
params={'username': self.username_field.verbose_name},
)
else:
self.confirm_login_allowed(self.user_cache)
return self.cleaned_data
def confirm_login_allowed(self, user):
if not user.is_active:
raise forms.ValidationError(
self.error_messages['inactive'],
code='inactive',
)
def get_user_id(self):
if self.user_cache:
return self.user_cache.id
return None
def get_user(self):
return self.user_cache
views.py:
@csrf_protect
@never_cache
def login(request, template_name='login.html',
authentication_form=AuthenticationForm,
extra_context=None):
if request.method == "POST":
form = authentication_form(request, data=request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse('student:mains'))
else:
print(form.errors)
else:
form = authentication_form(request)
context = {
'form': form,
}
return TemplateResponse(request, template_name, context)
我的登录模板:
<html>
<head><title>Login</title></head>
<strong> Mysite Login </strong>
<br><br>
<h3> Please Enter your credentials carefully </h3>
<body>
{% if form.errors %}
<p>NOT VALID</p>
{% for errors in form.errors %}
{{ errors }}
{% endfor %}
{% endif %}
<form method="post">
{% csrf_token %}
<label>Username: </label>
<input type="text">
<br>
<label>Password: </label>
<input type="password">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
my urls.py:
from django.conf.urls import url, patterns
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^password_change/$', auth_views.password_change, {'template_name': 'password_change_form.html', 'post_change_redirect': '/stu/password_change/done/'}, name="password_change"),
url(r'^password_change/done/$', auth_views.password_change_done, {'template_name': 'password_change_done.html'}, name="password_change_done"),
url(r'^restricted/', views.restricted, name='restricted'),
url(r'^mains/', views.mains, name = 'mains'),
]
我正在尝试在我的项目上实现django身份验证。我已经阅读了一些文档并制作了上述认证视图和表单。
问题是,当我使用正确的凭据提交登录表单时,它不会将我重定向到我的视图中指定的重定向位置。它没有做任何事情。
这是我尝试做的正确方法吗?因为我没有在这里使用模型表格。
请建议我纠正它的方法......
谢谢!提前...
仍面临同样的问题......
答案 0 :(得分:0)
改变这个:
<form method="post">
<label>Username: </label>
<input name="name">
<label>Password: </label>
<input name="phone">
to,
<form method="post" action="{% url 'login_url_name' %}">
<label>Username: </label>
<input name="username">
<label>Password: </label>
<input name="password">
答案 1 :(得分:0)
调试建议:
login()
的开头添加调试日志 1 。如果您在提交时未看到日志记录,请务必将<form>
的{{1}}属性设置为正确的网址。action
测试。在视图中的is_valid()
分支内添加调试日志记录。如果它不起作用,请确保凭据正确无误。转储if form.is_valid():
以查看表单提交的数据可能出现的问题。 1 在您的代码中,调试日志记录可能只是一个简单的request.POST
。目的只是查看您的代码是否到达相关分支。如果你看到Django对你大喊大叫,你肯定会这样做。