所以我正在为我的Django应用程序创建一个登录系统。它在我的开发方面工作绝对正常,但是如果我提交正确的用户名和密码(它给出500错误),它就不起作用。我不确定我在views.py中指出的两行中哪一行是问题,但我认为它必须是其中之一,因为如果我确实输入了一个不正确的用户,那么即使在prod中我也能被重定向
我的开发和生产方面的代码完全相同 - 唯一的区别在于设置
DEBUG = True
ALLOWED_HOSTS = []
^以上是我的开发设置,但在prod中,DEBUG为False,并且ALLOWED_HOSTS已填写相应的名称。
在views.py中:
def user_login(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(request=request, user=user) <- This line
return render(request, 'site/homepage.html') <- Or this line
else:
return render(request, 'site/login.html', {'incorrect': True})
else:
return render(request, 'site/login.html', {})
在login.html中:
{% block content %}
{% if user.is_authenticated %}
<div class="title">
<h2>Error</h2>
</div>
<p>You have already logged in, {{ user.firstname }}. Please logout to login as another user!</p>
{% else %}
<div class="title">
<h2>Login</h2>
</div>
{% if incorrect %}
<p>You have entered the wrong username and/or password.<br />
Please try again</p>
{% elif unauthorised %}
<p>You must login before trying to access that page!<br /></p>
{% endif %}
<form id="login_form" method="post" action="#">
{% csrf_token %}
<label>Username: <input type="text" name="username" value="" size="50" /></label>
<br />
<label>Password: <input type="password" name="password" value="" size="50" /></label>
<br />
<input type="submit" value="submit" />
</form>
{% endif %}
{% endblock %}
答案 0 :(得分:0)
在表单中,action
属性没有任何值,因此您不会向视图发送任何内容。它应该是"."
<form id="login_form" method="post" action=".">
或
<form id="login_form" action="{% url 'login' %}" method="post">
如果您的登录网址名称为login
。
答案 1 :(得分:0)
在我的服务器上测试过这项工作,如果没有,请告诉我们新的错误。
view.py:
def login_user(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(request, user)
return HttpResponseRedirect('/')
else:
return render(request, 'login/auth.html', {'incorrect': True})
else:
return render(request, 'login/auth.html', {})