Django Auth 1.11问题:'login'模板不存在,登录表单无法运行
Hey there, I’ve been stuck on weird Django form issues like this before, so let’s break this down step by step—starting with the TemplateDoesNotExist error that pops up alternately when you refresh.
First, fix the TemplateDoesNotExist error
These are the most common culprits to check:
Double-check your template folder structure
Django looks for templates in a nested structure to avoid naming conflicts. Make yours looks like this:your_project/ your_app/ templates/ your_app/ login.html # Your login template lives hereIf you just have
templates/login.htmlwithout the inneryour_appfolder, Django might miss it unless your app is properly registered.Confirm your app is in
INSTALLED_APPS
Opensettings.pyand make sure your app is listed in theINSTALLED_APPSlist. Without this, Django won’t scan your app’s template folder at all:INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', # ... other default apps 'your_app_name', # Add this line if it's missing! ]Verify your view’s template path
If you’re using a custom function-based view, make sure you’re passing the full template path:def login_view(request): # ... form logic here ... return render(request, 'your_app/login.html', {'form': form})If you’re using Django’s built-in
LoginView, don’t forget to set thetemplate_nameattribute:from django.contrib.auth.views import LoginView class CustomLoginView(LoginView): template_name = 'your_app/login.html' # Critical line!Clear Django’s cache and restart the server
Sometimes Django caches old template paths. Run this command to clear it:python manage.py clearcacheThen fully stop and restart your development server—cached files can stick around even after clearing.
Next, fix the alternating refresh errors
Weird alternating issues usually happen when your view handles GET/POST requests incorrectly. For example, if you don’t return the template when the form is invalid, or skip checking request.method. Make your view follows this pattern:
from django.contrib.auth import authenticate, login from django.contrib.auth.forms import AuthenticationForm from django.shortcuts import render, redirect def login_view(request): if request.method == 'POST': form = AuthenticationForm(request, data=request.POST) if form.is_valid(): user = form.get_user() login(request, user) return redirect('home') # Redirect after successful login # If form is invalid, fall through to render the form with errors else: form = AuthenticationForm() # Always return the template—for GET requests OR invalid POST return render(request, 'your_app/login.html', {'form': form})
If you skip returning the template in the invalid POST case, Django might send an empty response, causing odd behavior when you refresh.
If you can share the exact second error message or snippets of your urls.py/template code, we can narrow this down even more!
内容的提问来源于stack exchange,提问作者New2Python

