django 模板不存在

django TemplateDoesNotExist

我想做一个注册页面,当用户点击注册时,它会检查两个密码是否相同,如果不相同,则在"confirm password"后给出错误信息。

但是当我在 views.py 中调用 "return render(request, reverse("accounts:signup"), {'form': signup_form}) " 时,它显示了一个错误,追溯是:

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/accounts/signup_post/

Django Version: 1.7
Python Version: 2.7.5
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'accounts')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:

Traceback:
File "/Users/feizhao/.virtualenvs/nahan/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/feizhao/dropbox/nahan/accounts/views.py" in signup_post
  64.     return render(request, reverse("accounts:signup"), {'form': signup_form})
File "/Users/feizhao/.virtualenvs/nahan/lib/python2.7/site-packages/django/shortcuts.py" in render
  48.     return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/Users/feizhao/.virtualenvs/nahan/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
  170.         t = get_template(template_name, dirs)
File "/Users/feizhao/.virtualenvs/nahan/lib/python2.7/site-packages/django/template/loader.py" in get_template
  144.     template, origin = find_template(template_name, dirs)
File "/Users/feizhao/.virtualenvs/nahan/lib/python2.7/site-packages/django/template/loader.py" in find_template
  136.     raise TemplateDoesNotExist(name)

Exception Type: TemplateDoesNotExist at /accounts/signup_post/
Exception Value: /accounts/signup/

我的帐户应用程序看起来像:

$ tree -L 3 accounts
accounts
├── __init__.py
├── admin.py
├── forms.py
├── locale
│   └── zh_CN
├── migrations
│   ├── 0001_initial.py
│   ├── __init__.py
├── models.py
├── static
│   └── accounts
│       └── login.css
├── templates
│   └── accounts
│       ├── base.html
│       ├── login.html
│       └── signup.html
├── tests.py
├── urls.py
├── views.py

urls.py:

urlpatterns = patterns(
    '',
    url(r'^accounts/', include('accounts.urls', namespace="accounts")),
    url(r'^admin/', include(admin.site.urls)),
)

accounts/urls.py:

urlpatterns = patterns(
    '',
    url(r'^login/$', views.login, name='login'),
    url(r'^signup/$', views.signup, name='signup'),
    url(r'^login_post/$', views.login_post, name='login_post'),
    url(r'^signup_post/$', views.signup_post, name='signup_post'),
)

signup_post views.py 中的函数:

def signup_post(request):
    if request.method == 'POST':
        signup_form = forms.SignupForm(request.POST)

        if signup_form.is_valid():
            signup_info = signup_form.cleaned_data
            username = signup_info['username']
            email = signup_info['email']
            password = signup_info['password_1']
            user = User.objects.create_user(
                username=username,
                email=email,
                password=password)
            user.save()

    else:
        signup_form = forms.SignupForm()

    return render(request, reverse("accounts:signup"), {'form': signup_form})

我已阅读 Django TemplateDoesNotExist 和其他类似问题,但没有帮助!

ps:我问过关于注册的问题,也许有用。

这里的问题是

reverse("accounts:signup")

returns an url,请参阅此处 (https://docs.djangoproject.com/en/1.7/ref/urlresolvers/#reverse),而您需要模板路径,因此您应该 return:

return render(request, 'accounts/signup.html', {'form': signup_form})

您必须在 setings.py 文件中设置模板目录路径, 请将下面的代码粘贴到您的 settings.py 文件中。

import os

PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))

TEMPLATE_DIRS = (
    os.path.join(PROJECT_PATH,'templates'),
)

此外,当您 return 响应时,您必须在视图中传递模板名称。

return render(request, 'accounts/signup.html', {'form': signup_form})

问题是 reverse() 函数 returns url(来自 urls.py)。所以 render() 的参数看起来像这样:

return render(request, '/signup/', {'form': signup_form}) # look at 'singup' path at url.py

您必须对模板路径进行硬编码。

return render(request, 'accounts/signup.html', {'form': signup_form})