首页 > 解决方案 > 无法从 Django 中的给定位置加载模板

问题描述

我无法使用以下网址加载 product_create.html

http://127.0.0.1:8000/create/

以下是错误 在此处输入图像描述

正如您在标题Template-loader postmortem下的最后一行中看到的那样,它正在我的模板所在的以下位置搜索模板(检查项目布局)。

C:\trydjango\products\templates\products\product_create.html

以下是我的项目布局

以下是我的项目布局.

settings.py 的相关部分

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR),"templates"],
        #'DIRS': [path.joinpath(BASE_DIR, "templates")],
        #'DIRS': [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',
            ],
        },
    },
]

网址.py

from django.contrib import admin
from django.urls import path
from pages.views import home_view, contact_view, about_view
from products.views import product_detail_view,product_create_view
#its better fom the alternate version
#from pages import views and then using views.home_view

urlpatterns = [
    path('', home_view ,name = 'home'),
    #the 1st argument to path gives the url
    path('admin', admin.site.urls),
    path('contact/', contact_view ,name = 'contact'),
    path('about/', about_view ,name = 'about'),
    path('product/', product_detail_view),
    path('create/', product_create_view),
]

产品/views.py

from django.shortcuts import render
from .forms import ProductForm
from .models import Product
# Create your views here.



def product_create_view(request):
    form = ProductForm(request.POST or None)
    if form.is_valid():
        form.save()

    context={
        'form':form
    }

    return render(request,"products/product_create.html",context)


def product_detail_view(request):
    obj=Product.objects.get(id=1)
    # context={
    #   'title':obj.title,
    #   'description':obj.description
    # }                 
    context={
        'object':obj
    }

    return render(request,"products/product_detail.html",context)

标签: pythondjango

解决方案


推荐阅读