我想从Django教程向mysite / polls项目添加一个帐户应用程序。当我添加“帐户”应用程序来管理用户身份验证时,我无法正确设置网址。
我的根URLconf是:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
# Examples:
# url(r'^$', 'uniVote.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^elections/', include('elections.urls', namespace='elections')),
url(r'^admin/', include(admin.site.urls)),
# ex: accounts/...
url(r'^accounts/', include('accounts.urls')),
)
我的帐户应用中的URLconf是:
from django.conf.urls import patterns, url
urlpatterns = patterns(
'',
# ex: /accounts/login/
url(r'^accounts/login/$', 'accounts.views.user_login'),
# ex: /accounts/logout/
url(r'^accounts/logout/$', 'accounts.views.user_logout'),
# ex: /accounts/register/
url(r'^accounts/register/$', 'accounts.views.user_register'),
)
此外,这是我的帐户views.py:
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render_to_response
from django.core.context_processors import csrf
#Import a user registration form
from accounts.forms import UserRegisterForm
# User Login View
def user_login(request):
if request.user.is_anonymous():
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
#This authenticates the user
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
#This logs him in
login(request, user)
else:
return HttpResponse("Not active")
else:
return HttpResponse("Wrong username/password")
return HttpResponseRedirect("/")
# User Logout View
def user_logout(request):
logout(request)
return HttpResponseRedirect('/')
# User Register View
def user_register(request):
if request.user.is_anonymous():
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid:
form.save()
return HttpResponse('User created succcessfully.')
else:
form = UserRegisterForm()
context = {}
context.update(csrf(request))
context['form'] = form
#Pass the context to a template
return render_to_response('accounts/register.html', context)
else:
return HttpResponseRedirect('/')
每当我将浏览器指向:0.0.0.0:8080/accounts/register时,我收到404错误并输出以下内容:
使用uniVote.urls中定义的URLconf,Django按以下顺序尝试了这些URL模式:
当前网址(accounts / register /)与其中任何一个都不匹配。
从教程中,我相信addr:port / accounts / register会加载root URLconf并查看'accounts'并加载accounts / urls.py并传递'register'并查看第三个url模式并加载帐户。 views.user_register。
我有什么东西可以到达帐户/ ...网址吗?
答案 0 :(得分:3)
目前,您的应用已配置为在accounts/accounts/register/
网址中查看。
从您的代码中,URL的正则表达式重复了“帐户”。
基本上你应该尝试:
url(r'^accounts/', include('accounts.urls'))
然后从帐户网址中删除“帐户”。
urlpatterns = patterns(
'',
# ex: /accounts/login/
url(r'^login/$', 'accounts.views.user_login'),
# ex: /accounts/logout/
url(r'^logout/$', 'accounts.views.user_logout'),
# ex: /accounts/register/
url(r'^register/$', 'accounts.views.user_register'),
)