我遇到了一个问题,即“不存在”的网址能够显示。例如,我转到 /myapp/login 的一个 url,它可以工作。然后我去 /myapp/login/login ,它仍然有效。然后我去 /myapp/insertrandomcharactershere/login 它仍然有效。这适用于我在 /myapp/ 的子路径中的每个 url,因此 /myapp/register、/myapp/login 和 /myapp/myaccount。似乎只要它以我的 urlconf 中的名称结尾,它就可以工作。我一直无法解决这个问题,所以我从我的登录页面和我的 urlconfs 添加了一些代码,希望能包含这个问题。
对于不是 /myapp/、/myapp/login/、/myapp/register/、/myapp/myaccount/ 的任何内容,我都应该 404
http://paste.pound-python.org/show/31613/
#django/urls.py
urlpatterns = patterns('',
url(r'myapp/', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls)),
)
#myapp/urls.py
urlpatterns = patterns('myapp.views',
url(r'^$', 'index', name='index'),
url(r'register/$', 'register', name='register'),
url(r'myaccount/$', 'myaccount', name='myaccount'),
url(r'login/$', 'login_page', name='login'),
url(r'logout/$', 'logout_user', name='logout')
)
#myapp/login.py
def login_page(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('index'))
form = LoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data['username']
username = username.capitalize()
password = form.cleaned_data['password']
try:
User.objects.get(username=username)
except:
return render(request, 'myapp/login.html', {
'form': form,
'error': "Account doesn't exist"
})
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('index'))
else:
return render(request, 'myapp/login.html', {
'form': form,
'error': 'Account is disabled or banned',
})
else:
return render(request, 'myapp/login.html', {
'form': form,
'form': 'Authentication Error!'
})
return render(request, 'myapp/login.html', {
'form': form,
})
{% if not user.is_authenticated %}
#myapp/templates/myapp/login.html
<strong>Login</strong>
<form action='{% url 'login' %}' method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Login">
</form>
{{ error }}
{% endif %}