****** 听我说,我知道这有点长,我讨厌听起来像这样,但我还没睡4天这个是我学校项目的一部分,所以我真的很感激任何输入 ******
您好,我对Django来说相对较新,但是,我已经从youtube的教程和教程中反弹,Django文档试图弥补这一点。我已经创建了民意调查应用程序,并且还创建了其他几个应用程序,但是当我几乎完成时,他们都完全空白,我必须START ALL 过了。在这一点上,我只是对Django 累,但我愿意继续,因为我真的讨厌退出。
无论如何这不是这个问题的关键(尽管如果你可以帮助让我的应用程序重新启动并再次运行那就太棒了!我会在下面放一个链接。)
在尝试学习如何登录页面后,我最近的应用程序崩溃后。我开始了另一个名为accounts的应用程序,它将专门用于登录/注销/注册。然而,到目前为止,事情并没有变得很好。
我开始在youtube上关注一个教程,但随后出现了一大堆我无法解决的错误,必须处理缩进和内容。所以我用另一个教程启动了我的应用程序,就在这里:https://www.youtube.com/watch?v=BIgVhBBm6zI
我试图查看我的错误(这是我的输入字段没有显示出来的事实),并试图转到下一个登录页面背后的逻辑。但我知道有另一个错误。现在错误消息不起作用,每当我点击提交时,都没有任何反应。页面只是 BASICALLY 刷新。我知道我还没有足够深入注册部分,这将允许我实际登录,但我期待某种错误信息告诉我,我没有一个帐户或什么的。
对于我的输入字段,我尝试了几件事(包括此post)并且没有任何效果。远程接近的唯一事情就是我在Html中手动输入字段(我知道我不应该这样做)或将form.html链接到表单模板,该表单模板只检查用户是否在字段中放置了内容与否(这也不起作用)。
以下是我的代码的样子,如果你还在阅读,那么感谢你对我的影响到目前为止。 (另请注意,注释掉的部分是我之前尝过的内容)
views.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",{})
forms.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)
form.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 %}
形状template.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'),
]
我网站的图片:
This is me manually putting in the fields
This is when I include the form template
如图所示,一切都刚刚关闭,我不想再重新启动,因为时间不够,而且我将失败。
已更新基础
{% 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>
答案 0 :(得分:1)
问题是即使表单已提交,您也在渲染模板。试试这个:
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")
这是一个有用的link
答案 1 :(得分:1)
以下是我如何显示默认登录表单(添加{{form.as_p}}
)
form.html
{% extends 'accounts/base.html' %}
{% block main_content %}
<div class="container">
<div class='col-sm-6 col-sm-offset-3'>
<h1>{{ title }}</h1>
<form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}
{{ form.as_p }}
<input type='submit' class='btn btn-default' value='{{ title }}' />
</form>
</div>
</div>
{% endblock %}
同样在base.html中,包括完整的bootstrap + jquery
<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>
然后在views.py
中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)
# or any other success page
return HttpResponse("Logged in")
return render(request, "accounts/form.html", {"form":form, "title": title})