为什么Django没有渲染Django应用目录中的HTML文件?

voj3qocg  于 2023-02-14  发布在  Go
关注(0)|答案(2)|浏览(222)

**我是djando的新手,在django框架中构建了我的第一个项目应用程序“accounts”。“accounts”应用程序有一个templates\accounts文件夹,所有的.html文件都在其中。问题是,django正在渲染所有的.html文件,除了位于我的templates目录中的reso.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']

我试着在www.example.com中设置TEMPLATE变量setting.py,这样django就可以从我的目录中搜索模板,但是每次都抛出相同的错误。

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

Below is an image showing the location of my .html files:-
Setting.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

bbuxkriu

bbuxkriu1#

您需要将app添加到settings.py中的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
]
kupeojn6

kupeojn62#

我遇到了这个问题,return render()函数不接受我的html文件作为参数,我通过做两件事来解决它:
1.在 settings.py模板DIRS中,我更改为[“模板”](之前我有[“另一个dirinsidemydjangofiles\模板”]
1.我把templates文件夹移到了主项目目录(它是Django项目文件夹的一个子目录,根本没有渲染)。

相关问题