我遇到的问题是“不存在”的网址能够显示。例如,我在/ myapp / login访问一个url,它可以工作。然后我去/ myapp / login / login,它仍然有效。然后我去/ myapp / insertrandomcharactershere / login,它仍然有效。这将适用于我的子路径/ myapp / so / myapp / register,/ myapp / login和/ myapp / myaccount中的每个URL。似乎只要它以我的urlconf中的名称结尾就可以了。我一直无法解决这个问题所以我从我的登录页面和我的urlconfs中添加了一些代码,这些代码应该包含问题。
我应该404任何不是/ myapp /,/ myapp / login /,/ myapp / register /,/ myapp / myaccount /
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 %}
答案 0 :(得分:5)
我认为网址缺少^
:
以下行:
url(r'login/$', 'login_page', name='login'),
应该是:
url(r'^login/$', 'login_page', name='login'),
答案 1 :(得分:0)
您需要在您的网址中指定它应该以您在开始时使用'^'
所需的字符串开头。
所以你可以更新你的urls.py行
url(r'myapp/', include('myapp.urls')),
到
url(r'^myapp/', include('myapp.urls')),
您可能希望对myapp.urls
中的其他网址执行此操作。
答案 2 :(得分:0)
您需要使用&#39; ^&#39;。
标记模式的开头例如:
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')
)