简体   繁体   English

带有芹菜的django中的TemplateDoesNotExist错误

[英]TemplateDoesNotExist error in django with celery

I am learning to use celery with django through this tutorial .我正在通过本教程学习在 django 中使用 celery。 In this tutorial, the person is developing a webscraping tool with django and celery.在本教程中,此人正在使用 django 和 celery 开发一个网页抓取工具。 I am trying to follow the tutorial but I am facing the following error message我正在尝试按照教程进行操作,但遇到以下错误消息

TemplateDoesNotExist at /
home.html, scraping/products_list.html

this is how my files are arranged这就是我的文件的排列方式

.
├── celerybeat-schedule.db
├── celerydjangotutorial
│   ├── __init__.py
│   ├── asgi.py
│   ├── celery.py
│   ├── settings.py
│   ├── templates
│   │   ├── base.html
│   │   └── home.html
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
├── db.sqlite3
├── manage.py
└── scraping
    ├── __init__.py
    ├── admin.py
    ├── apps.py
    ├── migrations
    │   ├── 0001_initial.py
    │   ├── 0002_auto_20200827_0735.py
    │   ├── __init__.py
    │   └── __pycache__
    │       ├── 0001_initial.cpython-38.pyc
    │       ├── 0002_auto_20200827_0735.cpython-38.pyc
    │       └── __init__.cpython-38.pyc
    ├── models.py
    ├── tasks.py
    ├── tests.py
    └── views.py

where celerydjangotutorial is the django project and scraping is a django application.其中celerydjangotutorial是Django项目和拼抢Django应用程序。 In the tutorial, the person places the templates into the project directory.在教程中,此人将模板放入项目目录中。 he also creates a views file in the project directory.他还在项目目录中创建了一个视图文件。 I followed him as he does in the tutorial.我跟着他,就像他在教程中所做的那样。 here is my code.这是我的代码。

celerydjangotutorial/urls.py celerydjangotutorial/urls.py

from django.contrib import admin
from django.urls import path, include
from .views import HomePageView

urlpatterns = [
    path('', HomePageView.as_view(), name='home'),
    path('admin/', admin.site.urls),
]

celerydjangotutorial/views.py celerydjangotutorial/views.py

from django.shortcuts import render
from django.views import generic
from scraping.models import Products

class HomePageView(generic.ListView):
    template_name = 'home.html'
    context_object_name = 'products'

    def get_queryset(self):
        return Products.objects.all()

scraping/models.py抓取/models.py

from django.db import models

class Products(models.Model):
    title = models.CharField(max_length=200)
    link = models.CharField(max_length=2083, default="", unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    website = models.CharField(max_length=30, default="", blank=True, null=True)

scraping/tasks.py抓取/tasks.py

import time
import json
from datetime import datetime

from celery import Celery
from celery.schedules import crontab
from celery import shared_task

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.keys import Keys

@shared_task
def scrape():
    try:
        print('starting the scraping process')
        product_list = []
        url = f'https://www.amazon.com/s?k=chips&ref=nb_sb_noss_2'

        driver = webdriver.Chrome('./chromedriver')

        driver.get(url)
        driver.implicitly_wait(15)

        links = driver.find_elements_by_class_name("a-size-mini")
        for link in links:

            element = WebDriverWait(driver, 5).until(
                EC.presence_of_element_located((By.LINK_TEXT, link.text)))

            product_meta = {
                'link': element.get_attribute('href'),
                'website': 'amazon'
            }

            product_list.append(product_meta)

        print('scraping process completed')
        return save_function(product_list)

    except Exception as e:
        print('scraping failed')
        print(e)

@shared_task(serializer='json')
def save_function(product_list):
    print('saving extracted data')
    new_count = 0

    for product in product_list:
        try:
            Products.objects.create(
                title = product['title'],
                link = product['link'],
                website = product['website']
            )
            new_count += 1

        except Exception as e:
            print('failed at latest_product is None')
            print(e)
            break

    return print('finished')

celerydjangotutorial/celery.py celerydjangotutorial/celery.py

from __future__ import absolute_import
import os
from celery import Celery
from celery.schedules import crontab

os.environ.setdefault('DJANGO_SETTINGS_MODULE','celerydjangotutorial.settings')

app = Celery('celerydjangotutorial')
app.conf.timezone = 'UTC'
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()

settings.py设置.py

...

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

...

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['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',
            ],
        },
    },
]

...

CELERY_BROKER_URL = 'amqp://localhost:5672'
CELERY_RESULT_BACKEND = 'amqp://localhost:5672'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'UTC'

I am not sure what I am doing wrong.我不确定我做错了什么。 I followed most of the tutorial.我遵循了大部分教程。 Except for tasks.py the rest of the code is similar to his code.除了tasks.py,其余代码与他的代码类似。 Please help me.请帮我。

Thanks in advance提前致谢

[EDIT-1] posting the entire error [EDIT-1] 发布整个错误

Internal Server Error: /
Traceback (most recent call last):
  File "/Users/sashaanksekar/anaconda3/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/sashaanksekar/anaconda3/lib/python3.8/site-packages/django/core/handlers/base.py", line 145, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/sashaanksekar/anaconda3/lib/python3.8/site-packages/django/core/handlers/base.py", line 143, in _get_response
    response = response.render()
  File "/Users/sashaanksekar/anaconda3/lib/python3.8/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/Users/sashaanksekar/anaconda3/lib/python3.8/site-packages/django/template/response.py", line 81, in rendered_content
    template = self.resolve_template(self.template_name)
  File "/Users/sashaanksekar/anaconda3/lib/python3.8/site-packages/django/template/response.py", line 63, in resolve_template
    return select_template(template, using=self.using)
  File "/Users/sashaanksekar/anaconda3/lib/python3.8/site-packages/django/template/loader.py", line 47, in select_template
    raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: home.html, scraping/products_list.html

Try adding app name under templates folder and move HTML files into it.尝试在模板文件夹下添加应用程序名称并将 HTML 文件移动到其中。 So it should be like templates/celerydjangotutorial/ base.html home.html所以它应该像 templates/celerydjangotutorial/base.html home.html

检查文件、文件夹和路径的名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM