我是Django的初学者,我正在努力学习。我想不通错误的原因,模板名称是按照文档中student_detail.html定义的。我的直觉是细节视图找不到学生模型.或者没有正确实现细节视图
错误
TemplateDoesNotExist at /student/login/
/student/5/detail/
Request Method: POST
Request URL: http://127.0.0.1:8000/student/login/
Django Version: 3.0.2
Exception Type: TemplateDoesNotExist
Exception Value:
/student/5/detail/
Exception Location: C:\Users\Madhu\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\loader.py in get_template, line 19
Python Executable: C:\Users\Madhu\Anaconda3\envs\MyDjangoEnv\python.exe
Python Version: 3.8.1
Python Path:
['D:\\python\\DJANGO_COURSE_2.xx\\Practice1\\Library',
'C:\\Users\\Madhu\\Anaconda3\\envs\\MyDjangoEnv\\python38.zip',
'C:\\Users\\Madhu\\Anaconda3\\envs\\MyDjangoEnv\\DLLs',
'C:\\Users\\Madhu\\Anaconda3\\envs\\MyDjangoEnv\\lib',
'C:\\Users\\Madhu\\Anaconda3\\envs\\MyDjangoEnv',
'C:\\Users\\Madhu\\Anaconda3\\envs\\MyDjangoEnv\\lib\\site-packages']
Server time: Thu, 30 Apr 2020 06:12:11 +0000
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
This engine did not provide a list of tried templates.
urls.py
from django.urls import path
from . import views
#Url patterns
app_name = 'students'
urlpatterns=[
path('signup/',views.studentsignup, name='signup'),
path('<int:pk>/detail/',views.StudentDetailView.as_view(),name='detail'),
path('login/',views.loginPage, name='login'),
]
视图.py
def loginPage(request):
if request.method=='POST':
#if request method is post
form = Login(request.POST)
print('method is post')
if form.is_valid():
# if form is valid then
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = User.objects.get(email=email)
print('user is authenticated',user)
if user is not None:
# if user exists then
login(request,user)
print('student login done')
return render(request,reverse('students:detail',args=[user.student.id]))
else:
# if user has entered invalid Credentials or not present
print('invalid Credentials')
message = 'Invalid Credentials or SignUp'
form = Login()
return render(request,'students/login.html',context={'message':message,'form':form})
else:
print('invalid form')
message = 'Invalid form'
return render(request,'students/login.html',context={'message':message,'form':form})
else:
#if request method is get
form = Login()
return render(request, 'students/login.html',{'form':form})
class StudentDetailView(generic.DetailView,mixins.LoginRequiredMixin):
model = Student
template_name = 'students/students_detail.html'
模型.py
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
# Create your models here.
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.TextField(max_length=256)
roll_no = models.IntegerField()
branch = models.CharField(max_length=5)
sem = models.IntegerField(default=1)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('students:detail',kwargs={'pk':self.pk})
设置.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
[enter image description here][1]
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y$y!x0%h9v+1crht_qmp_x2)1hy9r&m-m05f6hz#3@x4)ap-8h'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'books.apps.BooksConfig',
'students.apps.StudentsConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'library.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'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',
],
},
},
]
WSGI_APPLICATION = 'library.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
你需要显示项目studcture和settings.py。
你的模板在应用程序文件夹中吗?
在应用程序所在的目录下创建一个名为templates的文件夹(那里有admin.py),并将所有的模板转移到该文件夹中,确保你有这些设置在你的manage.py中。
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'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',
],
},
},
]
并在安装的应用程序列表中添加你的应用程序名称。确保在urls.py中只引导文件名而不是路径。