我的views.py就是这个
from django.contrib.auth import authenticate, login
from django.shortcuts import render_to_response
def login(request):
def errorHandle(error):
form = LoginForm()
return render_to_response('login.html', {
'error' : error,
'form' : form,
})
if request.method == 'POST': # If the form has been submitted...
form = LoginForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
# Redirect to a success page.
login(request, user)
return render_to_response('courses/logged_in.html', {
'username': username,
})
else:
# Return a 'disabled account' error message
error = u'account disabled'
return errorHandle(error)
else:
# Return an 'invalid login' error message.
error = u'invalid login'
return errorHandle(error)
else:
error = u'form is invalid'
return errorHandle(error)
else:
form = LoginForm() # An unbound form
return render_to_response('login.html', {
'form': form,
})
urls.py就是这个
url(r'^userprof/login/$', 'django.contrib.auth.views.login', {'template_name': 'userprof/login.html'}),
模板login.html就是这个
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
{% endblock %}
我得到的错误就是这个
Reverse for ''django.contrib.auth.views.login'' with arguments '()' and keyword arguments '{}' not found.
错误是什么。以及如何删除它?
答案 0 :(得分:1)
问题更新了很多。请参阅此答案的评论中的新答案。
模板不应该也不能处理身份验证用户。您需要将表单提交给视图。 django.auth.contrib提供了开箱即用的视图。查看:https://docs.djangoproject.com/en/dev/topics/auth/
答案 1 :(得分:1)
在文档中,有一个名为login_required decorator的函数。 我认为这对你来说应该是最简单的方式。