Django投票应用出现TemplateDoesNotExist错误,请求技术支持
TemplateDoesNotExist Error in Your Django Polls App Let's work through this problem step by step—there are a few key issues with your template structure, view code, and template syntax that are causing the error.
1. Fix the Template Directory Structure (Root Cause of TemplateDoesNotExist)
Django follows a specific convention for template organization to automatically locate your files. Your current structure is non-standard:
polls/ template/ template/ polls/ template.html
Correct the Structure
Restructure your templates to match Django's expected layout (this will let Django find your template without extra configuration):
polls/ templates/ <!-- Note the plural "templates" --> polls/ <!-- Subdirectory matching your app name --> template.html
2. Update the View's Template Path
Your view currently references "polls/template.html"—this path is correct for the standard structure above. If you can't adjust the directory structure right now, you'd need to use the full relative path to your template:
return render(request, "template/template/polls/template.html", context)
But using the standard structure is strongly recommended to avoid future issues.
3. Verify Django's Template Settings
Double-check your settings.py to ensure it's configured to find app-specific templates:
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], # Leave empty unless you need global templates 'APP_DIRS': True, # Critical: tells Django to look in app-specific templates folders 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # Also make sure your polls app is in INSTALLED_APPS INSTALLED_APPS = [ # ... default Django apps 'polls', ]
4. Fix Template Variable Mistakes (Even if Template Loads, These Will Break It)
Your template has mismatched variable names and invalid syntax that will cause errors once the template loads:
Corrected Template Code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Polls Index</title> </head> <body> {% if latest_questions %} <!-- Matches the context variable from your view --> <ul> {% for question in latest_questions %} <!-- Fixed variable name --> <li><a href='/polls/{{ question.id }}/'><b>{{ question.ques_text }}</b></a></li> <!-- Fixed question_id to question.id --> {% endfor %} </ul> {% else %} <p>No polls are available right now.</p> <!-- Added fallback for empty polls --> {% endif %} </body> </html>
5. Cleanup Unnecessary Changes
You mentioned trying render_to_response, removing the request parameter, and adding paths to DIRS—these aren't needed if you follow the steps above. Revert those changes to keep your code standard.
内容的提问来源于stack exchange,提问作者LionCoder

