python - DJANGO 登录 // INPUT FIELDS 不工作 // 错误消息不显示
问题描述
******听我说,我知道这有点长,我讨厌听起来像这样,但我已经 4 天没睡了,这是我上学项目的一部分,所以我真的很感激任何输入这个******
你好,我对 Django 比较陌生,但尽管如此,我一直在 youtube 上从教程跳到教程,Django 文档试图弥补这一点。我已经创建了投票应用程序,并且还在创建其他几个应用程序,但是当我几乎完成的时候,它们完全变成了空白,我不得不从头开始。在这一点上,我对 Django 有点厌倦了,但我愿意继续,因为我真的很讨厌放弃。
无论如何,这不是这个问题的目的(尽管如果你能帮助我的应用程序重新启动并运行,那就太好了!我会在下面放一个链接)。
在尝试学习如何创建登录页面后,我最近的应用程序崩溃后。我启动了另一个名为accounts的应用程序,它专门用于登录/注销/注册。然而,到目前为止,事情的进展并不顺利。
我开始关注 youtube 上的一个教程,但后来出现了一大堆我无法摆脱的错误,不得不处理缩进之类的东西。所以我从另一个教程开始我的应用程序,这就是这里:https ://www.youtube.com/watch?v=BIgVhBBm6zI
我尝试查看我的错误(这是我的输入字段未显示的事实),并尝试转到下一个,这是登录页面背后的逻辑。但是我知道有另一个错误。现在错误消息不起作用,每当我单击提交时,什么都没有发生。该页面基本上会刷新。而且我知道我对注册部分还不够深入,这将允许我实际登录,但我期待某种错误消息告诉我我没有帐户或其他东西。
对于我的输入字段,我尝试了几件事(包括这篇文章),但没有任何效果。唯一可以远程接近的事情是我在 Html 中手动输入字段(我知道我不应该这样做)或将 form.html 链接到表单模板,该模板仅检查用户是否在字段中放入了某些内容(这也不起作用)。
这是我的代码的样子,如果你还在阅读这篇文章,非常感谢你到目前为止对我的包容。(另请注意,注释掉的部分是我之前尝试过的东西)
视图.py
from django.contrib.auth import (
authenticate,
get_user_model,
login,
logout,
)
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from .forms import UserLoginForm
# Create your views here.
def login_view(request):
title = "Login"
form = UserLoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get('password')
return render(request, "accounts/form.html", {"form":form, "title": title})
# def authentication(request):
# if request.method == 'POST':
# title = "Login"
# form = UserLoginForm(request.POST)
# if form.is_valid():
# cd = form.cleaned_data
# user = authenticate(username=cd['username'],
# password=cd['password'])
# if user is not None:
# if user.is_active:
# login(request, user)
# #return HttpResponse('Authenticated ' \
# # 'successfully')
# return HttpResponseRedirect('accounts/home.html/')
# else:
# return HttpResponse('Disabled account')
# else:
# return HttpResponse('Invalid login')
# else:
# form = UserLoginForm()
# return render(request, 'accounts/form.html', {'form': form})
def register_view(request):
return render(request,"accounts/form.html",{})
def logout_view(request):
return render(request,"accounts/form.html",{})
表格.py
from django import forms
from django.contrib.auth import (
authenticate,
get_user_model,
login,
logout,
)
User = get_user_model()
class UserLoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username', 'email', 'password')
def clean(self,*args,**kwargs):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
user = authenticate(username=username,password=password)
if not user:
raise forms.ValidationError("This user does not exist")
if not user.check_password(password):
raise forms.ValidationError("Incorrect Password")
if not user.is_active:
raise forms.ValidationError("This user is no longer active.")
return super(UserLoginForm, self).clean(*args,**kwargs)
表单.html
{% extends 'accounts/base.html' %}
{% block main_content %}
<div class="container">
<h2 class="form-signin-heading">{{ title }}</h2>
<form method='POST' action='' enctype='multipart/form-data' class="form-signin">
{% csrf_token %}
<!--{% include 'accounts/form-template.html' %}-->
<h2 class="h3 mb-3 font-weight-normal">Please sign in</h2>
<label for="username" class="sr-only">Username</label>
<input type="username" id="username" class="form-control" placeholder="Username" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit" value="{{ title }}">Sign In</button>
</form>
</div>
<!--<div class='col-sm-6 col-sm-offset-3'>-->
<!-- <h1>{{ title }}</h1>-->
<!-- <form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}-->
<!-- <input type='submit' class='btn btn-default' value='{{ title }}' />-->
<!-- </form>-->
<!--</div>-->
{% endblock %}
表单模板.html
{% for field in form %}
<div class="form-group">
<div class="col-sm-12">
<span class="text-danger small">{{ field.errors }}</span>
</div>
<label class="control-label col-sm-2">{{ field.label_tag }}</label>
<div class="col-sm-10">{{ field }}</div>
</div>
{% endfor %}
base.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Accounts</title>
<link rel="stylesheet" type="text/css" href="{% static 'accounts/bootstrap-3.3.7-dist/css/bootstrap.min.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'accounts/signin.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'accounts/style.css' %}" />
</head>
<body>
<div class="jumbotron">
<div class="container">
{% block main_content %}
{% endblock %}
</div>
</div>
</body>
</html>
settings.py(重要部分的小预览)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
INSTALLED_APPS = [
'accounts',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',]
urls.py(对于我的网站不是应用程序)
from django.conf.urls import url, include
from django.contrib import admin
from accounts.views import (login_view, register_view, logout_view)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/', login_view, name='login'),
# url(r'^login/', authentication, name='authentication'),
]
我的网站图片:
这就是我所说的帖子中的 StackOverflow 修复的样子(是的,就是这样,白色方块实际上是按钮)
如图所示,一切都刚刚结束,我不想再次重新开始,因为根本没有足够的时间,我将不及格。
更新基础
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Accounts</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="{% static 'accounts/signin.css' %}" />
</head>
<body>
<div class="jumbotron">
<div class="container">
{% block main_content %}
{% endblock %}
</div>
</div>
</body>
</html>
解决方案
问题是即使提交了表单,您也正在渲染模板。试试这个:
def login_view(request):
title = "Login"
form = UserLoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
return render(request, "accounts/form.html", {"form":form, "title": title})
将您的 form.html 输入更改为:
<input name="username" type="username" id="username" class="form-control" placeholder="Username" required autofocus>
<input name="password" type="password" id="inputPassword" class="form-control" placeholder="Password" required>
同样在您的 UserLoginForm 更改字段中,如果无效()将失败:
fields = ("username", "password")
这是一个有用的链接
推荐阅读
- react-native - 解析服务器应用程序,只有一个管理员用户可以通过 Facebook 登录更改数据
- excel - 通过 OraOLEDB 运行存储过程
- r - 如何解决 r 中的 mlr、rose 和 caret 错误
- jdbc - QueryRunner 返回“ORA-00972:标识符太长”,将值作为参数传递
- reactjs - 如何模拟 Material-ui withStyles 的实现?
- json - 如何使用 Rest API 从 powershell 获取、删除或发布 wordpress 4.9 帖子?
- json - 如果嵌套数组为空,jq 不返回任何内容
- javascript - 动态更新以编程方式创建的链接(例如 – Blob)
- android - 如何在 Instagram 应用程序上实现视图(不在图像上)的模糊/霜/纤维背景效果
- c# - NetworkInfo.IsConnected 对象引用未设置为 xamarin 上的对象实例