【问题标题】:Why Django is not rendering some HTML files from Django app directory?为什么 Django 不从 Django 应用程序目录呈现一些 HTML 文件?
【发布时间】:2021-04-05 05:51:37
【问题描述】:

我是 djando 的新手,我在 django 框架中构建了我的第一个项目应用程序“accounts”。 'accounts' 应用程序有一个 templates\accounts 文件夹,所有 .html 文件都驻留在该文件夹中。问题是,django 正在渲染除我的模板目录中的 reso.html 之外的所有 .html 文件。 在渲染 reso.html 时,在 URL 栏中输入 http://127.0.0.1:8000/masterdata/ 时会引发以下错误:

OSError at /masterdata/
[Errno 22] Invalid argument: 'C:\\Users\\Parijat\\Desktop\\Theis project\\CRM\\accounts\\templates\\accounts\reso.html'
Request Method: GET
Request URL:    http://127.0.0.1:8000/masterdata/
Django Version: 3.1.4
Exception Type: OSError
Exception Value:    
[Errno 22] Invalid argument: 'C:\\Users\\Parijat\\Desktop\\Theis project\\CRM\\accounts\\templates\\accounts\reso.html'
Exception Location: C:\Users\Parijat\Desktop\Theis project\env\lib\site-packages\django\template\loaders\filesystem.py, line 23, in get_contents
Python Executable:  C:\Users\Parijat\Desktop\Theis project\env\Scripts\python.exe
Python Version: 3.9.0
Python Path:    
['C:\\Users\\Parijat\\Desktop\\Theis project\\CRM',
 'c:\\users\\parijat\\appdata\\local\\programs\\python\\python39\\python39.zip',
 'c:\\users\\parijat\\appdata\\local\\programs\\python\\python39\\DLLs',
 'c:\\users\\parijat\\appdata\\local\\programs\\python\\python39\\lib',
 'c:\\users\\parijat\\appdata\\local\\programs\\python\\python39',
 'C:\\Users\\Parijat\\Desktop\\Theis project\\env',
 'C:\\Users\\Parijat\\Desktop\\Theis project\\env\\lib\\site-packages']

我尝试在 setting.py 中设置 TEMPLATE 变量,以便 django 可以从我的目录中搜索模板,但每次都会抛出相同的错误。比如我改了

'DIRS': [], to 'DIRS': [BASE_DIR / 'accounts'],

Below is an image showing the location of my .html files:-

设置.py

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'ss3@*&2)-+e!3bxok+afpflc&j!e(6tz^z_+80a*yh)oos8@m!'

DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    
    'accounts.apps.AccountsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    
    
]

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 = 'CRM.urls'

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',
                
            ],
        },
    },
]

WSGI_APPLICATION = 'CRM.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

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',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'

MEDIA_URL='/images/'

STATICFILES_DIRS=[

os.path.join(BASE_DIR, 'static')

]

urls.py@同setting.py所在的项目目录

from django.contrib import admin
from django.urls import path, include
from django.http import HttpResponse

urlpatterns = [
   
    path('admin/', admin.site.urls),
    path('', include('accounts.urls'))
    

]

urls.py@apps.py 和 admin.py 所在的位置

from django.urls import path
from . import views
urlpatterns = [
   
    path('', views.home, name = 'home'),
    path('customers/<str:pk_test>/', views.customer, name = 'customers'),
    path('product/', views.product, name= 'product' ),
    path('create/', views.create_order, name = 'create'),
    path('create/<str:pk>/', views.UpdateOrder, name = 'updateorder'),
    path('delete/<str:pk>/', views.deleteorder, name = 'delete'),
    path('plan_production/', views.planproduction),
    path('masterdata/', views.masterdata1),
]

Views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from . models import *
from . forms import OrderForm
from django.template import Context, Template
from django.template.loader import *


# Create your views here.
def home(request):
    order_model = orders.objects.all()
    customers_model = customers.objects.all()
    total_customers = customers_model.count()
    total_orders = order_model.count()
    delivered = order_model.filter(status='delivered').count()
    pending = order_model.filter(status='pending').count()
    context = {'order':order_model, 'customers': customers_model, 'total_customers': total_customers, 'total_orders': total_orders, 'delivered': delivered, 'pending': pending}
    
    return render(request, 'accounts\index.html', context)

def customer(request, pk_test):

    customer_model = customers.objects.get(id=pk_test)
    order_model = customer_model.orders_set.all()
    order_count = order_model.count()
    context = {'customer':customer_model, 'order':order_model, 'total_order':order_count}
    return render(request, 'accounts\customers.html', context) 

def product(request):
    
    product_model = products.objects.all()
    return render(request, 'accounts\products.html', {'products':product_model}) 

    
def create_order(request):

    form = OrderForm() 
    if request.method == 'POST':
         form = OrderForm(request.POST)
    if  form.is_valid():
        form.save()
        return redirect('/')


    context = {'form': form}
    return render(request, 'accounts\order_form.html', context)

def UpdateOrder(request, pk):
    order = orders.objects.get(id=pk)
    form = OrderForm(instance=order)
    if request.method == 'POST':
         form = OrderForm(request.POST, instance= order)
    if  form.is_valid():
        form.save()
        return redirect('/')
    context = {'form':form}
    return render(request,'accounts\order_form.html', context)    

def deleteorder(request,pk):
    order = orders.objects.get(id=pk)
    if request.method == 'POST':
         order.delete()
         return redirect('/')
    context = {'item': order}
    return render(request,'accounts\delete.html', context)    

def planproduction(request):
        return render(request,'accounts\plan_production.html')  


def masterdata1(request):
    return render(request,'accounts\reso.html')  

reso.html

{% extends 'accounts/main.html' %}
{%load static%}
{% block content %}

<div class="card-deck">
    <div class="card text-white bg-primary mb-3" style="max-width: 18rem;">
                  <div class="card-header">Master Data</div>
                    <div class="card-body">
                        <h5 class="card-title">Resource Mater Data</h5>
                        <p class="card-text">Add new resources or Update the existing resources</p>
                        <a href="#" class="primary stretched-link"></a>
                    </div>
    </div>
    
    
    <div class="card text-white bg-success mb-3" style="max-width: 18rem;">
                <div class="card-header">Master Data</div>
                    <div class="card-body">
                       <h5 class="card-title">Skills Mater Data</h5>
                       <p class="card-text">Add new skills</p>
                       <a href="#" class="primary stretched-link"></a>
                    </div>
    </div>
</div>   
{% endblock %} 

Project name-CRM Django app-accounts Below is an image of the project structure

【问题讨论】:

  • 你已经尝试过使用:'DIRS': [os.path.join (BASE_DIR, 'templates')],
  • 是的,我做到了,但是没有用
  • 请记住,模板是您创建所有 html 的文件夹,在您的情况下,创建地毯模板,然后从那里开始调用您的 html,例如您的应用程序中的模板/帐户/file.html
  • 试试DIRS': [BASE_DIR / 'accounts/templates']

标签: python-3.x django django-templates


【解决方案1】:

您需要在settings.py 中将app 添加到INSTALLED_APPS 设置

INSTALLED_APPS = [
    'accounts.apps.AccountsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts' # <- here
]

【讨论】:

  • 感谢您的评论,但是错误仍然存​​在。我想知道 . 的总数是否有任何限制。 app目录下可以使用的html文件?
  • 不,没有限制的html文件的数量,您可以将您的项目结构添加到您的问题中吗?
  • 尝试将html 文件从accounts 文件夹移到templates 文件夹中
猜你喜欢
  • 1970-01-01
  • 2013-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-17
  • 2017-11-22
  • 2011-09-18
  • 2019-07-27
相关资源
最近更新 更多